C# Task 暫停與取消
1.聲明參數
1 CancellationTokenSource _cancelSource= new CancellationTokenSource(); 2 CancellationToken _cancelToken= tokenSource.Token; 3 ManualResetEvent _resetEvent = new ManualResetEvent(true);
2.定義Task
Task task = new Task(async () => { while (true) { if (_cancelToken.IsCancellationRequested) { return; } // 初始化為true時執行WaitOne不阻塞 _resetEvent.WaitOne(); // Doing something....... } }, token); task.Start();
3.暫停Task
_resetEvent.Reset();
4.繼續Task
_resetEvent.Set();
5.取消Task
_cancelSource.Cancel();
備注:任務取消后如果想重開任務,不能使用已經取消的token,需要重新聲明一個對象.