如何中止/取消TPL任務(wù)?在一個線程中,我創(chuàng)建了一些System.Threading.Task開始每一項任務(wù)。當我做一個.Abort()若要終止線程,任務(wù)不會中止。我如何傳送.Abort()我的任務(wù)?
3 回答

斯蒂芬大帝
TA貢獻1827條經(jīng)驗 獲得超8個贊
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(); }}
- 3 回答
- 0 關(guān)注
- 537 瀏覽
添加回答
舉報
0/150
提交
取消