I know this is a general question. But even after going through different articles, it is still confusing. I have a Windows form application. I read some data from a device through the serial port of the PC. For the proper data transfer, my application has to make frequent wait sometimes. (to make sure that there is no data loss). I tried Thread.Sleep()
and realized that my device lost the serial connection many times. I have seen explanations that a Timer
is an option but does a Timer
freeze the UI as well? Which is the best option in this case ( Sleep
or Task.Delay
or Timer
)?
private static System.Timers.Timer _delayTimer;
private static void delay(int Time_delay)
{
int i = 0;
_delayTimer = new System.Timers.Timer();
_delayTimer.Interval = Time_delay;
_delayTimer.AutoReset = false;
_delayTimer.Elapsed += (s, args) => i = 1;
_delayTimer.Start();
while (i == 0) { };
}
private async void delayAsync(int delaySec)
{
await Task.Delay(vals); //is it the right way of doing delay ?
}