Необходимо вызвать метод в другом классе с таймером и после этого вернуть управление основному частичному классу (пользовательский элемент управления) - PullRequest
0 голосов
/ 07 августа 2020

Пожалуйста go с помощью следующего кода, который является чрезмерным упрощением кода, который у меня есть. Мне нужно знать, как по истечении таймера вернуть управление основному классу пользовательского управления, желательно в том же случае в операторе switch.

public partial class ucClass : UserControl
{
    int A;
    Label labelTimer = new Label();
    
    sec secObj = new sec();
    
    public execute()
    {
        switch(A)
        {
        case 1:
            secObj.initiate(labelTimer, 10);
            break:
        case 2:
        ......
        }
    }
    
}
class sec
{
    public System.Windows.Forms.Timer timer;
    
    private Label labelTimer = new Label();
    private int expectedCount = 0;
    private int actualCount = 0;
    
    public void initiate(Label labelTimer, int count)
    {
        this.expectedCount = count;
        this.labelTimer = labelTimer;
        this.timer.Interval = 1000;
        startTimer();
    }
    
    private void startTimer()
    {
        this.timer.Start();
        this.timer.Tick += this.timerElapsed;
    }
    
    private void timerElapsed(object sender, EventArgs e)
    {
        this.timer.Dispose();
        if(expectedCount > actualCount)
        {
            this.actualCount += 1;
            this.labelTimer.Text = this.actualCount.ToString();
            this.startTimer();
        }
        else
        {
            //this is where I need to notify the main class that timer has expired and go to case 2
        }
    }
}

1 Ответ

0 голосов
/ 07 августа 2020

Вы можете добиться желаемого поведения с помощью событий:

public partial class ucClass : UserControl
{
    int A;
    Label labelTimer = new Label();
    
    sec secObj = new sec();

    public ucClass()
    {
        // Listen to event from timer
        secObj.TimerExpired += (sender, args) =>
        {
             A = args.Count;
             execute();
        };
    }

    public void execute()
    {
        switch(A)
        {
            case 1:
                secObj.initiate(labelTimer, 10);
                break:
            case 2:
                ......
        }
    }
    
}

class sec
{
    public System.Windows.Forms.Timer timer;

    public event EventHandler<TimerExpiredEventArgs> TimerExpired;
    
    private Label labelTimer = new Label();
    private int expectedCount = 0;
    private int actualCount = 0;
    
    public void initiate(Label labelTimer, int count)
    {
        this.expectedCount = count;
        this.labelTimer = labelTimer;
        this.timer.Interval = 1000;
        startTimer();
    }
    
    private void startTimer()
    {
        this.timer.Start();
        this.timer.Tick += this.timerElapsed;
    }
    
    private void timerElapsed(object sender, EventArgs e)
    {
        this.timer.Dispose();
        if(expectedCount > actualCount)
        {
            this.actualCount += 1;
            this.labelTimer.Text = this.actualCount.ToString();
            this.startTimer();
        }
        else
        {
            // Send event with count
            TimerExpired?.Invoke(this, new TimerExpiredEventArgs
            {
                Count = actualCount
            });

        }
    }
}

public class TimerExpiredEventArgs
{
    public int Count { get; set; }
}

Я бы порекомендовал изучить следующее;

  • Шаблон MVVM
    • Это позволит вам разделить UI logi c (передавая метки et c) и control logi c (таймеры et c).
  • Reactive Extensions ( https://github.com/dotnet/reactive)
    • Это позволит использовать очень простой таймер:
      Observable
         .Interval(TimeSpan.FromSeconds(1))
         .Subscribe(count => {
            labelTimer.Text = count.ToString();
            if (count > actualCount) {
              A = args.Count;
              execute();
            }
         });
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...