内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
在一个线程中,创建了一些System.Threading.Task
开始每一项任务。
当我做一个.Abort()
若要终止线程,任务不会中止。
如何传送.Abort()
我的任务?
下面是一个例子:
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(); } }
下面是一个示例代码来演示这一点:
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(); }