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

查看:116
本文介绍了使用 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 如下

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

但是在上面的指定行,它表明重新抛出的异常未处理.我正在用适当的 try/catch 将我的 await 包装在上面的第一个代码片段中,为什么这个 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?

推荐答案

这里有一个 Microsoft Connect 对同一问题的支持请求.在

工具->选项->调试->一般

解决问题.

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

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