【问题标题】:Correct Way to Throw and Catch Exceptions using async/await使用 async/await 抛出和捕获异常的正确方法
【发布时间】: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


【解决方案1】:

这是support request for the same problem from Microsoft Connect。在

中禁用“只是我的代码”

工具->选项->调试->常规

解决问题。

【讨论】:

猜你喜欢
  • 2020-06-02
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 2020-06-18
  • 2014-03-16
  • 2016-02-07
  • 1970-01-01
  • 2020-10-17
相关资源
最近更新 更多