1、
CancellationTokenSource cancellationToken = new CancellationTokenSource();
public void InitData()
{
cancellationToken.Token.Register(() => { Name = "被取消了"; });
int count = 0;
Task.Run( () => {
while (!cancellationToken.IsCancellationRequested)
{
Name += $"{count}一直在执行...";
System.Console.WriteLine("一直在执行...");
Thread.Sleep(1000);
count++;
}
});
cancellationToken.CancelAfter(5000);
}
2、也可以写成
CancellationTokenSource cancellationToken = new CancellationTokenSource();
public void InitData()
{
cancellationToken.Token.Register(() => { Name = "被取消了"; });
int count = 0;
Task.Run(async () => {
while (!cancellationToken.IsCancellationRequested)
{
Name += $"{count}一直在执行...";
System.Console.WriteLine("一直在执行...");
await Task.Delay(1000);
count++;
}
});
cancellationToken.CancelAfter(5000);
}
标签:count,异步,Task,Name,cancellationToken,C#,CancellationTokenSource,计数器,...
From: https://www.cnblogs.com/guchen33/p/18475683