简体   繁体   English

C#异步调用方法定期

[英]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. 还有一个计时器,应该每隔10分钟调用一些应该运行异步的方法。

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. 如果这不是GUI应用程序,那么您可以使用System.Threading.Timer定期在不同的线程上执行代码。

If this is a WinForms/WPF app take a look at System.Windows.Forms.Timer and System.Windows.Threading.DispatcherTimer respectively. 如果这是一个WinForms / WPF应用程序,请分别查看System.Windows.Forms.TimerSystem.Windows.Threading.DispatcherTimer These are handy because they execute their code on the GUI thread, thus not needing explicit Invoke calls. 这些很方便,因为它们在GUI线程上执行代码,因此不需要显式的Invoke调用。

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. 最简单的方法是调用一个大功能,在这些动作之间休眠10分钟。 This doesn't block anything because it is in another thread. 这不会阻止任何东西,因为它在另一个线程中。

In .NET 4, you would do this with the Task class: 在.NET 4中,您可以使用Task类执行此操作:

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. 使用BackgroundWorker线程。

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 睡10分钟然后打电话给你的方法,重复一遍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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