简体   繁体   中英

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?

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.

The easiest way is to call one big function which sleeps for 10 minutes between the actions. This doesn't block anything because it is in another thread.

In .NET 4, you would do this with 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)

Use a BackgroundWorker thread.

void FireTask()
{
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerAsync();
}

void bw_DoWork(object sender, DoWorkEventArgs e)
{
    //Your job   
}

Start another thread that runs a loop

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

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