0

I am using System.Treading.Timer for Task which is checking some server status and setting label. I want to start this timer with button (start and repeat) and stop it after another button push. But I am unable to do that, I tried to play with AutoResetEvent object but I have trouble understanding how it works. Below is my code:

public class Main{
    Timer StatusWatch;
    int WatchStatusTime = 500;
    AutoResetEvent WatchReset = new AutoResetEvent(false);

    public Main(){
        StatusWatch = new System.Threading.Timer(StatusWatchCallBack, WatchReset,
            Timeout.Infinite, WatchStatusTime);
    }

    private async void StatusWatchCallBack(object state)
    {
        WatchReset.WaitOne();

        await Task.Run(() =>
        {
            lblPlcStatus.Dispatcher.Invoke(() =>
            {
                ...
                Timer work
                ...
            });
        });

        WatchReset.Set();
    }

    public void  ButtonClick(){
        if (client.Connected)
        {
            client.Disconnect();
            lblConnect.Content = "Connect";
        }
        else 
        { 
            if (client.ConnectTo(plc.IP, plc.Rack, plc.Slot) == 0)
            {
                lblConnect.Content = "Disconnect";
                WatchReset.WaitOne();
            }
                
        }
    }
}

I am not sure how to start this timer and how to end it. Is AutoResetEvent even usable for this?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Somachr
  • 464
  • 1
  • 8
  • 21
  • 1
    What is the reason for the `Task.Run`? It seems redundant to me. All it does is to invoke the `Dispatcher`. The `Task.Run` is mainly used to offload work to a background thread, and I can't see any such work to exist in the supplied code. – Theodor Zoulias Jan 18 '21 at 13:54
  • 1
    Is this in Winforms? If so: make your life easier and use `System.Windows.Forms.Timer`. – Fildor Jan 18 '21 at 14:13
  • @TheodorZoulias Yes it is redundant, thank you – Somachr Jan 18 '21 at 14:14
  • @Fildor WPF and I need Threading.Timer because it is async – Somachr Jan 18 '21 at 14:17
  • 1
    Ok, slightly more complicated. But what is async, here? The "Timer work"? – Fildor Jan 18 '21 at 14:21

1 Answers1

2

You can stop and restart a System.Threading.Timer simply by using the Change method:

StatusWatch.Change(Timeout.Infinite, Timeout.Infinite); // Stop

StatusWatch.Change(WatchStatusTime, WatchStatusTime); // Restart
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104