使用async / await正确抛出和捕获异常的方法

时间:2013-02-12 17:56:50

标签: c# multithreading exception-handling .net-4.5 async-await

全部,请使用以下代码:

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...
    }
}

但是在上面的指定行中,它表明重新抛出的异常未处理。 我正在使用相应的awaittry/catch打包在上面的第一个代码段中,为什么try/catch没有追踪重新抛出的异常?

1 个答案:

答案 0 :(得分:2)

这是support request for the same problem from Microsoft Connect。禁用“只是我的代码”#39;在

工具 - &gt; 选项 - &gt; 调试 - &gt; 常规

解决了这个问题。