Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 765
Jara Avatar asked Apr 12 '15 15:04

Jara


People also ask

What is the difference between Windows Forms timer and threading timer?

For Example, if a Delay Time is 2000 Milliseconds, then after the Timer creation, it will wait for 2 seconds before calling the Timer Callback. Unlike the Windows Forms’ Timer, the Threading Timer will invoke the Timer Callback in different thread

How to specify a delay or wait after the timer creation?

We can use "Due Time" to specify a delay or wait after the Timer creation. For Example, if a Delay Time is 2000 Milliseconds, then after the Timer creation, it will wait for 2 seconds before calling the Timer Callback. Unlike the Windows Forms’ Timer, the Threading Timer will invoke the Timer Callback in different thread

Should the timer component belong to the same thread?

Although this may be true, the only constraint is that the Timer Component should belong to the Same UI thread. The Timer Component from the Timer name space if useful when we want to achieve the Mixture of UI and System Tasks.

How to stop the timer from running in Java?

One can use the “Change ()” function on the Timer class to stop it. Have a look at the below code: In the above code, we are stopping the Timer by setting the Due Time and Period with “Timeout.Infinite” constant. This method call stops the Timer but at the same time currently running Timer Callback continues its execution and exits normally.


1 Answers

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);
like image 86
Jara Avatar answered Oct 18 '22 10:10

Jara