【发布时间】:2014-10-30 17:11:29
【问题描述】:
我有以下示例:(请同时阅读代码中的 cmets,因为它会更有意义)
public async Task<Task<Result>> MyAsyncMethod()
{
Task<Result> resultTask = await _mySender.PostAsync();
return resultTask;
// in real-life case this returns to a different assembly which I can't change
// but I need to do some exception handling on the Result in here
}
假设 _mySender 的 PostAsync 方法如下所示:
public Task<Task<Result>> PostAsync()
{
Task<Result> result = GetSomeTask();
return result;
}
问题是:
由于我没有在MyAsyncMethod 中等待实际的Result,如果PostAsync 方法抛出异常,那么将在哪个上下文中抛出和处理异常?
和
有什么方法可以处理我的程序集中的异常吗?
当我尝试将MyAsyncMethod 更改为:
public async Task<Task<Result>> MyAsyncMethod()
{
try
{
Task<Result> resultTask = await _mySender.PostAsync();
return resultTask;
}
catch (MyCustomException ex)
{
}
}
这里捕获了异常,如果没有等待实际结果的事件。碰巧PostAsync 的结果已经可用,并且在此上下文中抛出异常对吗?
是否可以使用ContinueWith 来处理当前类中的异常?例如:
public async Task<Task<Result>> MyAsyncMethod()
{
Task<Result> resultTask = await _mySender.PostAsync();
var exceptionHandlingTask = resultTask.ContinueWith(t => { handle(t.Exception)}, TaskContinuationOptions.OnlyOnFaulted);
return resultTask;
}
【问题讨论】:
-
您可能想查看 TPL 的 Exception Handling 页面。
标签: c# .net task-parallel-library async-await .net-4.5