简体   繁体   English

具有异步/等待的System.Threading.Timer陷入重复

[英]System.Threading.Timer with async/await stuck in repeat

I want to schedule a function to be executed every minute. 我想安排一个每分钟执行一次的功能。 This method calls an asynchronous function which is a HttpWebRequest. 此方法调用异步函数,该函数是HttpWebRequest。 I am using the async/await strategy: 我正在使用async / await策略:

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. 控制台打印“Tick”,但只打印一次。 It seems that the timer is stuck for some reason. 似乎计时器由于某种原因而卡住了。

After removing the async/await code the timer works fine though: 删除async / await代码后,计时器正常工作:

var timer = new System.Threading.Timer((e) =>
{
    Console.WriteLine("Tick");
}, null, 0, 5000);

Why does it not repeat and how can I implement the async/await strategy using a System.Threading.Timer? 为什么不重复,如何使用System.Threading.Timer实现async / await策略?

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. 正如Darin Dimitrov所指出的,异步方法中有一个异常,由于某种原因,它没有在调试器中显示,但可以使用try / catch捕获。

The following code using async/await works fine: 使用async / await的以下代码工作正常:

var timer = new System.Threading.Timer(async (e) =>
{
    await Task.Delay(500);
    Console.WriteLine("Tick");
}, null, 0, 5000);

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

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