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?