Reputation: 2780
Well i was wondering is using Task.Delay
is better that using Application.DoEvents ?
sample code:
private async void NonBlockingWaitAwhile(int milliseconds)
{
Stopwatch sWatch = Stopwatch.StartNew();
while (sWatch.Elapsed.Milliseconds <= milliseconds)
{
await Task.Delay(50);
}
}
or
private void WaitAwhile(int milliseconds)
{
Stopwatch sWatch = Stopwatch.StartNew();
while (sWatch.Elapsed.Milliseconds <= milliseconds)
{
Application.DoEvents();
}
}
So which method is better (specially that i'v heard that using Application.DoEvents may cause errors because it releases all the pending events the application may do)
Upvotes: 2
Views: 1733
Reputation: 4564
Application.DoEvents doesn't really create a delay - it forces the main application UI thread to process all the pending Windows messages in the queue. If there's not much to process, it returns very quickly.
Upvotes: 3
Reputation: 456437
Task.Delay
is better than DoEvents
because it avoids reentrancy.
However, the best solution is to use neither of them. Delays have only a few valid uses, e.g., throttling retries. The vast majority of the time I've seen a delay, it's wrong (e.g., the coder is using it to avoid a race condition or work around an awkward architecture, when the correct approach is to fix the actual problem).
Upvotes: 5