手动取消并释放Task资源

用取消令牌取消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);
        });
    }
}
posted @ 2024-09-25 16:18  不愿透露姓名的小村村  阅读(15)  评论(0编辑  收藏  举报