无法从Task.Run捕获异常

Jai*_*Jai 5 .net c# task async-await

我正在遵循此MSDN指南来处理Task中的异常。

这是我写的:

var myTask = Task.Run(() =>
    {
        throw new Exception("test");
    });
try
{
    myTask.Wait();
}
catch (Exception e)
{
    return false;
}
Run Code Online (Sandbox Code Playgroud)

我已经在catch块中设置了一个断点,但是在调试运行时,代码没有到达断点,这给了我:

用户代码未处理异常

我不知道发生了什么,因为我非常仔细地遵循了MSDN指南中的示例。实际上,我将示例复制到了我的项目中,但仍然存在相同的问题。

我可以在任务外处理异常的任何方法吗?如果任务是否抛出任何异常,我需要根据事实返回一个布尔值。

编辑

为了让您更清楚一些,这是一组更完整的代码:

public bool ConnectToService()
{
    try
    {
        // Codes for ServiceHost etc etc, which I'm skipping
        // These codes are already commented out for this test, so they do nothing

        var myTask = Task.Run(() =>
            {
                // Supposed to connect to a WCF service, but just throwing a test exception now to simulate what happens when the service is not running
                throw new Exception("test");
            });
        try
        {
            myTask.Wait();
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

    catch (Exception)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

呼叫者:

public void DoSomething()
{
    try
    {
        // Other irrelevant stuff
        if (ConnectToService())
        {
            DoAnotherThing();
        }
    }
    catch (Exception)
    {
    }

}
Run Code Online (Sandbox Code Playgroud)

我还想指出我对此有一个解决方案,但是令人困惑的是为什么MSDN的示例对我不起作用。我认为我自己的解决方案并不完美,因此我仍在寻找更优雅的解决方案。

Exception taskException = null;
var myTask = Task.Run(() =>
    {
        try
        {
            throw new Exception("test");
        }
        catch (Exception e)
        {
            taskException = e;
        }
    });
try
{
    myTask.Wait();
    if (taskException != null) throw taskException;
}
catch (Exception e)
{
    return false;
}
Run Code Online (Sandbox Code Playgroud)

小智 4

当任务运行时,它抛出的任何异常都会被保留,并在等待任务结果或任务完成时重新抛出

task.Wait()  Rethrows any exceptions

task.Result  Rethrows any exceptions
Run Code Online (Sandbox Code Playgroud)

同样,您的代码也可以正常工作

只需在捕获异常时按 f5,您就会发现这将明白您的意思