取消子任务时如何仅取消父任务?

时间:2015-10-14 17:46:26

标签: c# asp.net-mvc asynchronous task cancellationtokensource

我们有一个异步控制器操作,取消令牌作为参数:

 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服务),当其中一个被超时取消时,其他方法不会执行。

在3个Web服务中的每一个中,我也是异步连接到数据库。当第三个async子方法出错时,如何才能使async个任务中的两个有效?

我将取消令牌参数传递给父方法的所有async方法。

如果我不希望儿童行动影响我的父母行动的执行?但如果父母被取消,是否要取消?我该怎么办?

感谢您的关注和帮助

1 个答案:

答案 0 :(得分:1)

  

当第三个异步子方法出错时,如何让我的两个异步任务工作?

当任务被取消或因错误(例如超时)而完成时, final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile"; String token = null; try { token = GoogleAuthUtil.getToken(getApplicationContext(), Plus.AccountApi.getAccountName(mGoogleApiClient), "oauth2:" + SCOPES); } catch (IOException e) { Timber.e(e, "Error retrieving ID token."); } catch (GoogleAuthException e) { Timber.e(e, "Error retrieving ID token."); } 该任务将引发异常。

为避免传播异常,只需使用await / try

catch
  

但如果父母被取消,是否要取消?

你已经把父母的try { await SearchModel.GetRemains(search, NomenCode, ProducerName, _WithAnalog, this.HttpContext, cancelToken); } catch (MyExpectedException) { ... } 传了下来,所以这已经得到了解决。父项及其所有子项之间共享相同的取消令牌。

相关问题