如何在取消child个任务时只取消parent个任务?
how to cancel only parent tasks when cancelling child tasks?
我有一个以取消令牌作为参数的异步控制器操作:
public async Task<ActionResult> Index(string NomenCode = "", string ProducerName = "", bool? WithAnalog = null, long? OrderId = null, CancellationToken cancelToken = default(CancellationToken))
{
// .. some code
// my async method gets this token
await SearchModel.GetRemains(search, NomenCode, ProducerName, _WithAnalog, this.HttpContext, cancelToken);
//.. more code
}
SearchModel.GetRemains
方法调用其他 3 个异步方法(web-services),当其中一个被超时取消时,其他方法不会执行。
在这 3 个 Web 服务中的每一个中,我也异步连接到数据库。当第三个 async
child 方法出错时,如何使我的 async
任务中的两个工作?
我将取消标记参数从 parent 方法传递给所有 async
方法。
如果我根本不希望 child 操作影响我的 parent 操作的执行?但是,如果 parent 被取消了,想要它取消吗?我该怎么办?
感谢您的关注与帮助
How can I make 2 of my async tasks work when third one's async child method gets an error?
当任务被取消或完成时出现错误(例如超时),然后 await
执行该任务将引发异常。
为避免传播异常,只需使用 try
/catch
:
try
{
await SearchModel.GetRemains(search, NomenCode, ProducerName, _WithAnalog, this.HttpContext, cancelToken);
}
catch (MyExpectedException)
{
...
}
But want it to cancell if parent was cancelled?
您已经将父级的 CancellationToken
传下来了,所以这已经被处理好了。父项及其所有子项共享相同的取消令牌。
我有一个以取消令牌作为参数的异步控制器操作:
public async Task<ActionResult> Index(string NomenCode = "", string ProducerName = "", bool? WithAnalog = null, long? OrderId = null, CancellationToken cancelToken = default(CancellationToken))
{
// .. some code
// my async method gets this token
await SearchModel.GetRemains(search, NomenCode, ProducerName, _WithAnalog, this.HttpContext, cancelToken);
//.. more code
}
SearchModel.GetRemains
方法调用其他 3 个异步方法(web-services),当其中一个被超时取消时,其他方法不会执行。
在这 3 个 Web 服务中的每一个中,我也异步连接到数据库。当第三个 async
child 方法出错时,如何使我的 async
任务中的两个工作?
我将取消标记参数从 parent 方法传递给所有 async
方法。
如果我根本不希望 child 操作影响我的 parent 操作的执行?但是,如果 parent 被取消了,想要它取消吗?我该怎么办?
感谢您的关注与帮助
How can I make 2 of my async tasks work when third one's async child method gets an error?
当任务被取消或完成时出现错误(例如超时),然后 await
执行该任务将引发异常。
为避免传播异常,只需使用 try
/catch
:
try
{
await SearchModel.GetRemains(search, NomenCode, ProducerName, _WithAnalog, this.HttpContext, cancelToken);
}
catch (MyExpectedException)
{
...
}
But want it to cancell if parent was cancelled?
您已经将父级的 CancellationToken
传下来了,所以这已经被处理好了。父项及其所有子项共享相同的取消令牌。