CancellationTokenSource
和
CancellationToken
。 包含命名空間:
using System.Threading.Tasks;
。
class CancellationPractice
{
static void Main()
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
Myclass mc = new Myclass();
Task t = mc.RunAsync(token);
//Thread.Sleep(1000);
//cts.Cancel();
t.Wait();
Console.WriteLine($"Was Canceled:{token.IsCancellationRequested}");
Console.ReadKey();
}
}
class Myclass
{
public async Task RunAsync(CancellationToken ct)
{
if (ct.IsCancellationRequested) return;
await Task.Run(() => CycleMethod(ct), ct);
}
void CycleMethod(CancellationToken ct)
{
Console.WriteLine("開始執行 CyleMethod");
const int max = 5;
for (int i = 0; i < max; i++)
{
if (ct.IsCancellationRequested) return;
Thread.Sleep(2000);
Console.WriteLine($" {i + 1} of {max} 循環完成。");
}
}
}
取消主函數的兩行注釋後的輸出:
開始執行 CyleMethod
1 of 5 循環完成。
Was Canceled:True
可見隻完成了一項任務。
參考: