zoukankan      html  css  js  c++  java
  • C# Task 暂停与取消

    1.声明参数

    1 CancellationTokenSource tokenSource = new CancellationTokenSource();
    2 CancellationToken token = tokenSource.Token;
    3 ManualResetEvent resetEvent = new ManualResetEvent(true);

    2.定义Task

    Task task = new Task(async () => {
        while (true) {  
            if (token.IsCancellationRequested) {
                return;
            }
            
            // 初始化为true时执行WaitOne不阻塞
            resetEvent.WaitOne();
    
            // Doing something.......
            
            // 模拟等待100ms
            await Task.Delay(100);
        }
    
    }, token);
    
    task.Start();

    3.暂停Task

    resetEvent.Reset();

    4.继续Task

    resetEvent.Set();

    5.取消Task

    tokenSource.Cancel();

    备注:任务取消后如果想重开任务,不能使用已经取消的token,需要重新声明一个对象.

  • 相关阅读:
    GC原理---垃圾收集算法
    GC原理---对象可达判断
    散列算法和哈希表结构
    桶排序
    Spring事务梳理
    AQS
    重入锁
    CAS
    研究一下phpspider
    用php写爬虫去爬数据
  • 原文地址:https://www.cnblogs.com/zhengzc/p/10724839.html
Copyright © 2011-2022 走看看