Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# async call method periodically

Main thread of application is doing some work.

There also exists a timer, which should every 10 minutes call some method which should run asynchronous.

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

like image 883
Ksice Avatar asked Jun 25 '12 14:06

Ksice


1 Answers

I would not recommend using an explicit thread with a loop and sleep. It's bad practice and ugly. There are timer classes for this purpose:

If this is not a GUI app, then you can use System.Threading.Timer to execute code on a different thread periodically.

If this is a WinForms/WPF app take a look at System.Windows.Forms.Timer and System.Windows.Threading.DispatcherTimer respectively. These are handy because they execute their code on the GUI thread, thus not needing explicit Invoke calls.

The links also contain examples for each one.

like image 176
Tudor Avatar answered Sep 16 '22 11:09

Tudor