How do I abort/cancel TPL Tasks?

前端 未结 12 2285
佛祖请我去吃肉
佛祖请我去吃肉 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:51

    You can't. Tasks use background threads from the thread pool. Also canceling threads using the Abort method is not recommended. You may take a look at the following blog post which explains a proper way of canceling tasks using cancellation tokens. Here's an example:

    class Program
    {
        static void Main()
        {
            var ts = new CancellationTokenSource();
            CancellationToken ct = ts.Token;
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    // do some heavy work here
                    Thread.Sleep(100);
                    if (ct.IsCancellationRequested)
                    {
                        // another thread decided to cancel
                        Console.WriteLine("task canceled");
                        break;
                    }
                }
            }, ct);
    
            // Simulate waiting 3s for the task to complete
            Thread.Sleep(3000);
    
            // Can't wait anymore => cancel this task 
            ts.Cancel();
            Console.ReadLine();
        }
    }
    

提交回复
热议问题