Tsukasa
Tsukasa

Reputation: 6552

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?

Upvotes: 3

Views: 3923

Answers (1)

Softlion
Softlion

Reputation: 12585

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);

Upvotes: 4

Related Questions