用取消令牌取消Task
CancellationTokenSource
:取消令牌
cancellationTokenSource?.Cancel();
:其中?
表示判断cancellationTokenSource是否为null,如果不是null才取消,否则会造成找不到实例的异常
- 当
!cancellationToken.IsCancellationRequested
后则不再进入While循环中,最后等待Thread.Sleep(2000);
后Task资源被释放。
internal class Class1
{
private CancellationTokenSource cancellationTokenSource;
public void CancelTask()
{
cancellationTokenSource?.Cancel();
}
public void process()
{
cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;
Task.Run(() =>
{
while (!cancellationToken.IsCancellationRequested)
{
Thread.Sleep(1000);
}
Thread.Sleep(2000);
});
}
}