可以在任务方法中使用取消令牌吗?

Can cancellation token be used at tasks method within?

我刚刚开始处理任务,但我遇到了一些我不太了解的关于在任务中调用方法的事情。我开始了这样的新任务:

var ts = new CancellationTokenSource();
var token = ts.Token;

Task.Run(() => Control(), token);


void Control() 
{
     while(!token.IsCancellationRequested) 
     {
          token.ThrowIfCancellationRequested();

          switch(ENUM) 
          {

               case SOMETHING:

                 StartSomething();
               break;

          }


          Task.Delay(50, token).wait();
     }
 }

现在我不明白 StartSomething() 令牌被取消后的行为。如果 StartSomething() 也包含一个 while 循环,我也可以使用吗?

!token.IsCancellationRequested

token.ThrowIfCancellationRequested();

此外,如果在 StartSomething() 循环中抛出取消异常,它会立即取消任务吗?

是的,您可以轻松地将相同的标记传递给 StartSomething,它的异常将冒泡到 Control 并取消任务。如果你不这样做,那么它将保持 运行,即使 CancellationTokenwas cancelled until it returns control toControl` 观察令牌:

void StartSomething(CancellationToken token)
{
    while (true)
    {
        token.ThrowIfCancellationRequested(); // Will cancel the task.
        // ...
    }
}

请记住,token.ThrowIfCancellationRequested() 会引发异常并且任务会被取消,而 !token.IsCancellationRequested 只会完成任务而不会将其标记为已取消。