正确的方法抛出,并使用异步捕获异常/等待 [英] Correct Way to Throw and Catch Exceptions using async/await

查看:275
本文介绍了正确的方法抛出,并使用异步捕获异常/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有,请采取以下code:

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

从方法中 GenerateStage 我测试和重新抛出一个 OperationCancelledException 如下:

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

但在上述指定行,它指出,重新抛出的异常是未处理。 我包装我的等待第一code段以上相应的的try / catch ,这是为什么的try / catch 不诱重新抛出的异常?

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?

推荐答案

下面是一个<一个href=\"http://connect.microsoft.com/VisualStudio/feedback/details/522955/exceptions-thrown-in-tasks-are-incorrectly-considered-unhandled\"相对=nofollow>支持微软连接同样的问题请求。禁用只是我的code在

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

<大骨节病>工具 - > <大骨节病>选项 - > <大骨节病>调试 - > <大骨节病>常规

Tools->Options->Debugging->General

解决该问题。

这篇关于正确的方法抛出,并使用异步捕获异常/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆