C#Task取消任务执行CancellationTokenSource

目录

    • 参考代码1
    • 参考代码2

CancellationTokenSource这个是取消的发送信号,CancellationTokenSource每次传入Task.Run的时候必须是新的对象,不能是已经被调用了CancellationTokenSource.Cancle(true)了的,不然Task.Run不会启动

参考代码1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        /// 
        /// 取消任务信号
        /// 
        static CancellationTokenSource source = new CancellationTokenSource();
        static Task task1 = null;

        static void Main(string[] args)
        {
            Console.WriteLine("启动");
            TestTask();
            //2秒后取消task执行
            //Thread.Sleep(2000);
            //source.Cancel();

            //在指定的毫秒数后取消task执行
            source.CancelAfter(2 * 1000);
            //取消任务后,调用的委托
            source.Token.Register(() =>
            {
                //不延迟会获取不到正确的状态
                Thread.Sleep(50);
                Console.WriteLine("task1状态:" + task1.Status);
                Console.WriteLine("IsFaulted状态:" + task1.IsFaulted);
                Console.WriteLine("IsCompleted状态:" + task1.IsCompleted);
            });

            //Task.Run(() =>
            //{
            //    Task.Delay(3* 1000).Wait();
            //    Console.WriteLine("task1状态:" + task1.Status);
            //});

            Console.ReadKey();
        }
        public static void TestTask()
        {
            //CancellationTokenSource被使用过后必须要重新实例化(就是调用了一次CancellationTokenSource.cancellToken.Cancel(true);),不然下面的task不会执行启动
            task1 = Task.Run(() =>
            {
                Console.WriteLine("表示费时的操作");
                for (int i = 0; i < 100; i++)
                {
                    source.Token.ThrowIfCancellationRequested();
                    Console.WriteLine("执行中" + i);
                    Thread.Sleep(500);
                }
            }, source.Token);
        }

    }
}

执行结果:
启动
表示费时的操作
执行中0
执行中1
执行中2
执行中3
task1状态:Canceled
IsFaulted状态:False
IsCompleted状态:True

转载:
https://blog.csdn.net/htxhtx123/article/details/104192265

参考代码2

        
private static readonly object _obj = new object();
                
/// 
/// 是否正在运行,同一时间只允许一个线程处理数据接收
/// 
static bool isRuning = false;

static CancellationTokenSource cancellationSource = new CancellationTokenSource();

private void StartGetData()
{
    lock (_obj)
    {
        if (isRuning)
        {
            return;
        }
        isRuning = true;

        //注册任务取消, 
        cancellationSource = null;
        cancellationSource = new CancellationTokenSource();
     
       //注册任务取消后委托处理
        cancellationSource.Token.Register(() =>
        {
            Console.WriteLine("任务已取消" );
        });
 
        Task task = new Task(ReceiveHidDataFromDongle, cancellationSource.Token, TaskCreationOptions.LongRunning);
        task.Start();

        Console.WriteLine("启动成功");
    }
}

private void ReceiveHidDataFromDongle()
{
    while (true) // true
    {
        //结束任务 
        if (cancellationSource.IsCancellationRequested)
        {
            isRuning = false;
            Console.WriteLine("while退出" );
            break;
        }

       Console.WriteLine("自己的业务处理代码" );    

        Thread.Sleep(18);
    }
}

//USB断开连接触发
private void USBEventHandler(object sender, EventArrivedEventArgs e)
{
      //取消任务   
      cancellationSource.Cancel();
}

你可能感兴趣的:(C#,c#)