Correct Way to Throw and Catch Exceptions using async/await

我怕爱的太早我们不能终老 提交于 2019-12-10 19:46:09

问题


All, please take the following code:

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

From within method GenerateStage I test and re-throw a OperationCancelledException as follows

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

But at the specified line above, it is stating that the re-thrown exception is unhandled. I am wrapping my await in the first code snippet above with the appropriate try/catch, why is this try/catch not traping the re-thrown exception?


回答1:


Here is a support request for the same problem from Microsoft Connect. Disabling 'Just My Code' in

Tools->Options->Debugging->General

solves the problem.



来源:https://stackoverflow.com/questions/14838733/correct-way-to-throw-and-catch-exceptions-using-async-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!