System.Threading.Timer with async/await stuck in r

2019-04-30 18:36发布

问题:

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);

Why does it not repeat and how can I implement the async/await strategy using a System.Threading.Timer?

回答1:

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.

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);