【问题标题】:Can't handle exceptions in async method in Debug on Windows 7无法在 Windows 7 上的调试中处理异步方法中的异常
【发布时间】:2019-11-02 09:07:51
【问题描述】:

我正在努力解决仅在 Windows 7 的调试模式下出现的奇怪问题。 我试图捕捉我在方法 delcared async 中抛出的异常。是的,我正在等待它,但异常仍然存在于内部函数中。请参阅下面的代码。

  • 在应用配置中设置了所需的框架 (4.6.1) 版本。
  • 尝试设置 C# 语言的严格版本。
  • 在 Release 或 Windows 10 中运行良好。
  • 仅在 VS 2017 中测试。
private void Connect(int port)
{
    lock (apiLocker)
    {
        if (port <= 0)
        {
            throw new ArgumentException("Invalid port number");
        }
        //etc.
    }
}

internal async Task ConnectAsync(int port)
{
    await Task.Run(() =>
    {
        Connect(port);
    });
}

调用看起来像这样:

private async Task<bool> ConnectAsync()
{
    try
    {
        await RadioDispatcher.Instance.ConnectAsync(connectionSettings.Port);
        return true;
    }
    catch
    {
       //I can't reach that line in Debug on windows 7.
       //In Release on Windows 10 it works fine.
        return false;
    }
}

【问题讨论】:

  • 有什么例外?即使您不处理它,调试也总是会告诉您代码中出了什么问题。

标签: c# asynchronous exception


【解决方案1】:

TL;DR:这是 Visual Studio 调试的一个怪癖。抛出异常时点击继续,它就会被捕获。

更多细节:

async 方法的工作方式是async 状态机捕获异常并将其放置在返回的Task 上。后来,当你的代码awaits 那个Task 时,异常被提取并重新抛出。

但是,Visual Studio 具有特殊的调试逻辑,它会看到异常在离开您的代码之后被捕获,并且有点吓坏了,认为您的代码忽略了捕获该异常。 VS不理解异常是存储的,后面会观察。这就是为什么您会看到“未处理的异常”消息。

旁注:creating asynchronous wrappers for synchronous methods is an anti-pattern.

【讨论】:

    猜你喜欢
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2018-12-31
    • 2017-05-06
    • 2018-09-01
    • 2014-12-02
    • 2014-01-30
    相关资源
    最近更新 更多