A pattern for self-cancelling and restarting task

后端 未结 4 971
醉酒成梦
醉酒成梦 2020-11-30 01:38

Is there a recommended established pattern for self-cancelling and restarting tasks?

E.g., I\'m working on the API for background spellchecker. The spellcheck sessio

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 01:48

    Hope this will be useful - tried to create Helper class which can be re-used:

    class SelfCancelRestartTask
    {
        private Task _task = null;
        public CancellationTokenSource TokenSource { get; set; } = null;
    
        public SelfCancelRestartTask()
        {
        }
    
        public async Task Run(Action operation)
        {
            if (this._task != null &&
                !this._task.IsCanceled &&
                !this._task.IsCompleted &&
                !this._task.IsFaulted)
            {
                TokenSource?.Cancel();
                await this._task;
                TokenSource = new CancellationTokenSource();
            }
            else
            {
                TokenSource = new CancellationTokenSource();
            }
            this._task = Task.Run(operation, TokenSource.Token);
        }
    

提交回复
热议问题