Regularly execute the asynchronous method at a given interval

I need to publish some data to a service from a C # web application. Own data is collected when the user uses the application (type of usage statistics). I do not want to send data to the service during each user request, I would rather collect the data in the application and send all the data in one request in a separate thread that does not serve user requests (I mean the user does not need to wait until the request is processed service). To do this, I need an analog JS setInterval- start the function every X seconds to clear all collected data before the service.

I found out that the Timerclass provides somewhat similar ( Elapsed). However, this allows you to run the method only once, but this is not a big problem. The main difficulty is that this requires a signature

void MethodName(object e, ElapsedEventArgs args)

while I would like to run the async method that will call the web service (input parameters are not important):

async Task MethodName(object e, ElapsedEventArgs args)

Can anyone advise how to solve the described problem? Any advice appreciated.

+4
source share
2 answers

the equivalent asyncis a loop whilewith Task.Delay(which internally uses System.Threading.Timer):

public async Task PeriodicFooAsync(TimeSpan interval, CancellationToken cancellationToken)
{
    while (true)
    {
        await FooAsync();
        await Task.Delay(interval, cancellationToken)
    }
}

It’s important to pass CancellationTokenso that you can stop this operation whenever you want (for example, when you close the application).

, .Net , ASP.Net . (, HangFire), Fire and Forget ASP.NET ASP.NET Scott Hanselman

+12

- :

public async Task StartTimer(CancellationToken cancellationToken)
{

   await Task.Run(() => 
   {
      while (true)
      {
          DoSomething();
          await Task.Delay(10000, cancellationToken);
          if (ct.IsCancellationRequested)
              break;
      }
   });

}

, :

cancellationToken.Cancel();
+4

All Articles