How do I abort/cancel TPL Tasks?

前端 未结 12 2090
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 11:42

In a thread, I create some System.Threading.Task and start each task.

When I do a .Abort() to kill the thread, the tasks are not aborted.

12条回答
  •  太阳男子
    2020-11-22 11:55

    Aborting a Task is easily possible if you capture the thread in which the task is running in. Here is an example code to demonstrate this:

    void Main()
    {
        Thread thread = null;
    
        Task t = Task.Run(() => 
        {
            //Capture the thread
            thread = Thread.CurrentThread;
    
            //Simulate work (usually from 3rd party code)
            Thread.Sleep(1000);
    
            //If you comment out thread.Abort(), then this will be displayed
            Console.WriteLine("Task finished!");
        });
    
        //This is needed in the example to avoid thread being still NULL
        Thread.Sleep(10);
    
        //Cancel the task by aborting the thread
        thread.Abort();
    }
    

    I used Task.Run() to show the most common use-case for this - using the comfort of Tasks with old single-threaded code, which does not use the CancellationTokenSource class to determine if it should be canceled or not.

提交回复
热议问题