【发布时间】:2013-01-28 02:59:06
【问题描述】:
所有,请取以下代码:
Task<bool> generateStageAsyncTask = null;
generateStageAsyncTask = Task.Factory.StartNew<bool>(() =>
{
return GenerateStage(ref workbook);
}, this.token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
// Run core asynchroniously.
bool bGenerationSuccess = false;
try
{
bGenerationSuccess = await generateStageAsyncTask;
}
catch (OperationCancelledException e)
{
// Script cancellation.
result.RunSucceeded = true;
result.ResultInfo = "Script processing cancelled at the users request.";
return result;
}
从方法GenerateStage 中,我测试并重新抛出OperationCancelledException,如下所示
try
{
...
}
catch (Exception e)
{
if (e.GetType() == typeof(OperationCanceledException))
throw e;
else // <- Here it is saying that the thrown exception is unhandled.
{
// Do other stuff...
}
}
但是在上面的指定行,它表明重新抛出的异常未处理。 我用适当的try/catch 将我的await 包装在上面的第一个代码sn-p 中,为什么这个try/catch 没有捕获重新抛出的异常?
【问题讨论】:
-
你为什么不使用
catch(OperationCanceledException)? -
什么是
result,它在哪里定义和分配在哪里? -
您是否正在通过
token来自的CancelationTokenSource取消操作? -
result 用于在处理结束时向用户显示一些信息。我确实有
catch(OperationCancelledException),但将其切换到上面进行一些测试。是的,我正在使用CanellationTokenSource取消操作。感谢您的宝贵时间... -
对于近距离投票,这“不是一个真正的问题吗?”。这里要问的很简单。我在 await 周围使用的 Try/Catch 没有捕捉到重新抛出的异常 - 为什么??
标签: c# multithreading exception-handling .net-4.5 async-await