[英]how to use async and await in timer
My windows app's requirement are: 我的Windows应用程序的要求是:
Using HttpWebRequest get web request/response every 3 seconds in one thread.(total is about 10 threads for doing this web request/response.) 使用HttpWebRequest在一个线程中每3秒获取一次Web请求/响应(总共大约有10个线程用于执行此Web请求/响应。)
Each thread use some global variables. 每个线程使用一些全局变量。
I want to use a System.Timers.Timer and async and await. 我想使用System.Timers.Timer和async并等待。 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#.
我是C#的绿色。
You could write a RepeatActionEvery()
method as follows. 你可以编写一个
RepeatActionEvery()
方法,如下所示。
It's parameters are: 它的参数是:
action
- The action you want to repeat every so often. action
- 你想要经常重复的动作。 interval
- The delay interval between calling action()
. interval
- 调用action()
之间的延迟间隔。 cancellationToken
- A token you use to cancel the loop. cancellationToken
- 用于取消循环的标记。 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.
对于ASP应用程序,您可以从适当的位置调用它。
Note that you need a way to cancel the loop, which is why I pass a CancellationToken
to RepeatActionEvery()
. 请注意,您需要一种取消循环的方法,这就是我将
CancellationToken
传递给RepeatActionEvery()
。 In this sample, I use a cancellation source which automatically cancels after 8 seconds. 在此示例中,我使用取消源,在8秒后自动取消。 You would probably have to provide a cancellation source for which some other code called
.Cancel()
at the appropriate time. 您可能必须提供一个取消源,其中一些其他代码在适当的时候调用
.Cancel()
。 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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.