如何在计时器中使用异步和等待 [英] how to use async and await in timer
问题描述
我的Windows应用程序的要求是:
My windows app's requirement are:
-
使用HttpWebRequest每3秒在一个线程中获取一次Web请求/响应.(执行此Web请求/响应的总数大约为10个线程.)
Using HttpWebRequest get web request/response every 3 seconds in one thread.(total is about 10 threads for doing this web request/response.)
每个线程使用一些全局变量.
Each thread use some global variables.
我想使用System.Timers.Timer并异步并等待.但是我不知道这是获得高性能的最佳方法.然后如何测试它们.我在C#中是绿色的.
I want to use a System.Timers.Timer and async and await. But I don't know that is a best way for high performance. And then how to test them. I am a green in C#.
推荐答案
您可以编写如下的RepeatActionEvery()
方法.
You could write a RepeatActionEvery()
method as follows.
它的参数是:
-
action
-您要经常重复的操作. -
interval
-调用action()
之间的延迟间隔. -
cancellationToken
-用于取消循环的令牌.
action
- The action you want to repeat every so often.interval
- The delay interval between callingaction()
.cancellationToken
- A token you use to cancel the loop.
这是一个可编译的控制台应用程序,演示了如何调用它.对于ASP应用程序,您可以在适当的地方调用它.
Here's a compilable console application that demonstrates how you can call it. For an ASP application you would call it from an appropriate place.
请注意,您需要一种取消循环的方法,这就是为什么我将CancellationToken
传递给RepeatActionEvery()
的原因.在此示例中,我使用了一个取消来源,该来源会在8秒钟后自动取消.您可能必须提供一个取消源,在适当的时候为其提供其他一些称为.Cancel()
的代码. 有关详细信息,请参见此处.
Note that you need a way to cancel the loop, which is why I pass a CancellationToken
to RepeatActionEvery()
. In this sample, I use a cancellation source which automatically cancels after 8 seconds. You would probably have to provide a cancellation source for which some other code called .Cancel()
at the appropriate time. See here for more details.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
sealed class Program
{
void run()
{
CancellationTokenSource cancellation = new CancellationTokenSource(
TimeSpan.FromSeconds(8));
Console.WriteLine("Starting action loop.");
RepeatActionEvery(() => Console.WriteLine("Action"),
TimeSpan.FromSeconds(1), cancellation.Token).Wait();
Console.WriteLine("Finished action loop.");
}
public static async Task RepeatActionEvery(Action action,
TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
action();
Task task = Task.Delay(interval, cancellationToken);
try
{
await task;
}
catch (TaskCanceledException)
{
return;
}
}
}
static void Main(string[] args)
{
new Program().run();
}
}
}
这篇关于如何在计时器中使用异步和等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!