C#异步计数器的使用
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);
}