2017-09-25 132 views
0

我有一個正在運行的任務,需要製作一個功能,用戶可以隨時停止運行任務。我試圖token.Cancel();但仍然沒有工作。如何停止運行C#中的任務

這裏是我的代碼:

var task = new Task(new Action(Method), tokenSource2.Token); 
var cToken = tokenSource2.Token; 
cToken.Register(() => cancelNotification()); 

// code to stop the running task .. button click event 

if (tokenSource2 != null) 
      { 

       tokenSource2.Cancel(); 


      } 
+3

我相信取消令牌的工作方式被稱爲任務的主體需要接受取消令牌並不斷檢查它是否已在每一步邏輯之間被取消。 –

+2

任務取消是相互的。取消令牌不會奇蹟般地中止任務,任務本身必須檢查令牌是否被取消並正常退出。 – Equalsk

回答

2

我相信,取消標記工作,被調用的方法作爲任務的身體需要接受取消標記並不斷檢查它是否已經各自之間取消邏輯的一步。 See here for more details

本例摘自該文件,概述瞭如何檢查取消標記的狀態。

using System; 
using System.Threading; 

public class Example 
{ 
    public static void Main() 
    { 
     // Create the token source. 
     CancellationTokenSource cts = new CancellationTokenSource(); 

     // Pass the token to the cancelable operation. 
     ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeWork), cts.Token); 
     Thread.Sleep(2500); 

     // Request cancellation. 
     cts.Cancel(); 
     Console.WriteLine("Cancellation set in token source..."); 
     Thread.Sleep(2500); 
     // Cancellation should have happened, so call Dispose. 
     cts.Dispose(); 
    } 

    // Thread 2: The listener 
    static void DoSomeWork(object obj) 
    { 
     CancellationToken token = (CancellationToken)obj; 

     for (int i = 0; i < 100000; i++) { 
     if (token.IsCancellationRequested) 
     { 
      Console.WriteLine("In iteration {0}, cancellation has been requested...", 
           i + 1); 
      // Perform cleanup if necessary. 
      //... 
      // Terminate the operation. 
      break; 
     } 
     // Simulate some work. 
     Thread.SpinWait(500000); 
     } 
    } 
} 
// The example displays output like the following: 
//  Cancellation set in token source... 
//  In iteration 1430, cancellation has been requested... 
相關問題