Is there a Task based replacement for System.Threading.Timer?

前端 未结 7 1002
日久生厌
日久生厌 2020-11-27 09:49

I\'m new to .Net 4.0\'s Tasks and I wasn\'t able to find what I thought would be a Task based replacement or implementation of a Timer, e.g. a periodic Task. Is there such a

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 10:17

    It depends on 4.5, but this works.

    public class PeriodicTask
    {
        public static async Task Run(Action action, TimeSpan period, CancellationToken cancellationToken)
        {
            while(!cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(period, cancellationToken);
    
                if (!cancellationToken.IsCancellationRequested)
                    action();
            }
         }
    
         public static Task Run(Action action, TimeSpan period)
         { 
             return Run(action, period, CancellationToken.None);
         }
    }
    

    Obviously you could add a generic version that takes arguments as well. This is actually similar to other suggested approaches since under the hood Task.Delay is using a timer expiration as a task completion source.

提交回复
热议问题