c# - await 方法中的取消 token

标签 c# async-await async-ctp cancellation-token

将 token 放入任务的构造函数中的原因有很多,这里提到: Cancellation token in Task constructor: why?

使用关键字 async/await,它是如何工作的? 例如我的代码如下:

public async Task MethodAsync(CancellationToken token)
{
  await Method01Async();
  await Method02Async();
}

虽然是异步过程。我很快就使用了“Task.StartNext”或“Task.Run”或“new Task”。要能够指定我的取消 token ,我该怎么做?

最佳答案

您不应该在 async 方法中使用 Task 构造函数。通常,您只想传递 CancellationToken,如下所示:

public async Task MethodAsync(CancellationToken token)
{
  await Method01Async(token);
  await Method02Async(token);
}

关于c# - await 方法中的取消 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13822726/

相关文章:

rust - 如何在 Rust 中使用 Windows IOCP 实现异步函数?

C# 如何在异步方法中启动新的 "thread"?

python - 如何在类似 future 的对象的 __await__ 中等待?

c# - "async"关键字附近显示错误,但构建成功

c# - 如何更好地理解 "Async - Handling multiple Exceptions"文章中的代码/语句?

c# - 无法转换类型为 'System.IO.BufferedStream' 的对象

c# - LINQ Many to Many With In 或 Contains 子句(和扭曲)

c# - 带有 firefox 3.6 的 ajax modalpopupextender 显示在页面底部

c# - 可以赋值null吗?

c#-5.0 - C# 5 异步如何返回主线程?