Run async method regularly with specified interval

前端 未结 3 1862
渐次进展
渐次进展 2020-11-29 07:27

I need to publish some data to the service from the C# web application. The data itself is collected when user uses the application (a kind of usage statistics). I don\'t wa

3条回答
  •  情书的邮戳
    2020-11-29 07:59

    The simple way of doing this is using Tasks and a simple loop:

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

    When you want to stop the thread just abort the token:

    cancellationToken.Cancel();
    

提交回复
热议问题