Timer in Portable Library

后端 未结 6 888
我寻月下人不归
我寻月下人不归 2020-11-29 03:41

I can\'t find a timer in portable library / Windows Store. (Targeting .net 4.5 and Windows Store aka Metro)

Does any have an idea on how to created some kind of timi

6条回答
  •  无人及你
    2020-11-29 03:49

    I improved Ivan Leonenko answer by including a new parameter, which queue calls to you callback if the period is less than the callback run time. And replaced the legacy TimerCallback with an action. And finally, use our cancel token in the last delay, and used ConfigureAwait to increase concurrency, as the callback can be executed on any thread.

    internal sealed class Timer : CancellationTokenSource
    {
        internal Timer(Action callback, object state, int millisecondsDueTime, int millisecondsPeriod, bool waitForCallbackBeforeNextPeriod = false)
        {
            //Contract.Assert(period == -1, "This stub implementation only supports dueTime.");
    
            Task.Delay(millisecondsDueTime, Token).ContinueWith(async (t, s) =>
            {
                var tuple = (Tuple, object>) s;
    
                while (!IsCancellationRequested)
                {
                    if (waitForCallbackBeforeNextPeriod)
                        tuple.Item1(tuple.Item2);
                    else
                        Task.Run(() => tuple.Item1(tuple.Item2));
    
                    await Task.Delay(millisecondsPeriod, Token).ConfigureAwait(false);
                }
    
            }, Tuple.Create(callback, state), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
        }
    
        protected override void Dispose(bool disposing)
        {
            if(disposing)
                Cancel();
    
            base.Dispose(disposing);
        }
    }
    
        

    提交回复
    热议问题