C # asynchronous method call periodically

The main theme of the application does some work.

There is also a timer that every 10 minutes calls a method that must execute asynchronously.

Could you give me a good example of how to organize this?

+8
multithreading c # asynchronous timer
source share
4 answers

I would not recommend using an explicit thread with a loop and sleep. This is bad practice and ugly. For this purpose, there are timer classes:

If this is not a GUI application, you can use System.Threading.Timer to execute code in another thread periodically.

If this is a WinForms / WPF application, see System.Windows.Forms.Timer and System.Windows.Threading.DispatcherTimer respectively. This is convenient because they execute their code in the GUI thread, so it does not need explicit Invoke calls.

The links also contain examples for each of them.

+12
source share

The easiest way is to call one big function that sleeps for 10 minutes between actions. This does not block anything because it is in a different thread.

In .NET 4, you do this using the Task class:

 Task t = Task.Factory.StartNew(() => { /* your code here */ }); // or Task t = Task.Factory.StartNew(YourFunctionHere); void YourFunction() { while (someCondition) { // do something Thread.Sleep(TimeSpan.FromMinutes(10)); } } 

(this code has not been tested)

+1
source share

Use the BackgroundWorker stream.

 void FireTask() { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerAsync(); } void bw_DoWork(object sender, DoWorkEventArgs e) { //Your job } 
0
source share

Run another thread that starts the loop

Inside the loop; sleep for 10 minutes, then call your method, repeat

-2
source share

All Articles