I am currently running an async task on polling (meaning this async task is called every 1s). All other items need to update that fast, with exception of my async task below. This code works, but I wonder if it's good practice?
Note: _monitor only gets used by DoAsync()
private readonly object _monitor = new object();
private void PolledEverySecond()
{
_ = DoAsync(); // do this every 5 seconds
// Other stuff
GetNetworkState();
GetCurrentVelocity();
GetCurrentPosition();
Etc;
}
private async Task DoAsync()
{
await Task.Run(() =>
{
if (!Monitor.IsEntered(_monitor))
{
try
{
Monitor.Enter(_monitor);
DoStuff();
}
finally
{
Thread.Sleep(5000);
Monitor.Exit(_monitor);
}
}
});
}
The intention behind the Monitor.Enter/Monitor.Exit and the Thread.Sleep(5000). Is that DoAsync() does not get called every 1 second. I have a polling service that works great to update things and it's used by many of my ViewModels. But, in the case of DoAsync(), it is overkill to poll every second. Therefore, by making it async and using monitors, DoStuff() only gets called approximately every 5-6 seconds.