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
可见只完成了一项任务。
参考:
《C# 图解教程》异步
标签:异步,Console,CancellationToken,C#,IsCancellationRequested,取消,WriteLine,ct From: https://www.cnblogs.com/huvjie/p/16806374.html