Run async method regularly with specified interval

前端 未结 3 1860
渐次进展
渐次进展 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:57

    Here is a method that invokes an asynchronous method in periodic fashion:

    public static async Task PeriodicAsync(Func taskFactory, TimeSpan interval,
        CancellationToken cancellationToken = default)
    {
        while (true)
        {
            var delayTask = Task.Delay(interval, cancellationToken);
            await taskFactory();
            await delayTask;
        }
    }
    

    The supplied taskFactory is invoked every interval, and then the created Task is awaited. The duration of the awaiting does not affect the interval, unless it happens to be longer than that. In that case the principal of no-overlaping-execution takes precedence, and so the period will be extended to match the duration of the awaiting.

    In case of exception the PeriodicAsync task will complete with failure, so if you want it to be error-resilient you should include rigorous error handling inside the taskFactory.

    Usage example:

    Task statisticsUploader = PeriodicAsync(async () =>
    {
        try
        {
            await UploadStatisticsAsync();
        }
        catch (Exception ex)
        {
            // Log the exception
        }
    }, TimeSpan.FromMinutes(5));
    

提交回复
热议问题