C# Task的暂停与终止


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,需要重新声明一个对象.


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM