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?
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
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
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With