异步/等待中的System.Threading.Timer卡在重复中 [英] System.Threading.Timer with async/await stuck in repeat
问题描述
我想安排每分钟执行一次的功能.此方法调用一个异步函数,它是一个HttpWebRequest.我正在使用异步/等待策略:
I want to schedule a function to be executed every minute. This method calls an asynchronous function which is a HttpWebRequest. I am using the async/await strategy:
var timer = new System.Threading.Timer(async (e) =>
{
RSSClient rss = new RSSClient(listBoxRSS);
RSSNotification n = await rss.fetch();
// ...
Console.WriteLine("Tick");
}, null, 0, 5000);
控制台将打印滴答",但仅打印一次.看来计时器因某种原因被卡住了.
The console prints "Tick", but only once. It seems that the timer is stuck for some reason.
在删除异步/等待代码后,计时器仍然可以正常工作:
After removing the async/await code the timer works fine though:
var timer = new System.Threading.Timer((e) =>
{
Console.WriteLine("Tick");
}, null, 0, 5000);
为什么不重复,如何使用System.Threading.Timer实现异步/等待策略?
Why does it not repeat and how can I implement the async/await strategy using a System.Threading.Timer?
推荐答案
正如达林·迪米特洛夫(Darin Dimitrov)所指出的,由于某种原因,异步方法内部存在一个异常,该异常未在调试器中显示,但可以使用try捕获该异常./赶上.
As pointed out by Darin Dimitrov there was an exception inside of the async method that, for some reason, was not shown in the debugger but could be caught using try/catch.
以下使用async/await的代码可以正常工作:
The following code using async/await works fine:
var timer = new System.Threading.Timer(async (e) =>
{
await Task.Delay(500);
Console.WriteLine("Tick");
}, null, 0, 5000);
这篇关于异步/等待中的System.Threading.Timer卡在重复中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!