简体   繁体   中英

Proper way to delay code execution in a background worker

Ok so I've been reading up on Thread.Sleep, Task.Delay, AutoResetEvent ...etc

I see lots of arguments over which to use as it depends on the task being performed.

I currently use Thread.Sleep in everything and think I need to start avoiding it and use a better practice.

It's a client side app that contains a BackgroundWorker. The worker runs once every 30 minutes to check for updated data from a web service.

It then updates 3 int vars located in MainWindow. These don't do anything with the UI. They are just used in checks for other workers that are running.

Is one way to delay better than another?

If a user exit's the application and I'm calling Application.Current.Shutdown(), will it continue to run until Thread.Sleep has finished or will it exit even if a thread is sleeping?

use a combination of Task, await and CancellationTokenSource to be able to run in background, wait without wasting a thread, and cancel.

Something like:

var cancel = new CancellationTokenSource();
App.OnShutdown += (s,e) => cancel.Cancel();
await Task.Delay(1000,cancel.Token);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM