c# - 使用 .NET 任务并行库捕获错误

标签 c# exception error-handling task-parallel-library

这是我尝试过的两种捕获错误的替代方法,它们似乎都在做同样的事情..但一个比另一个更可取,为什么?

备选方案 1:

private async void BtnClickEvent(object sender, RoutedEventArgs e)
{

    try
    {
        Task t = Task.Run(() =>
            {
                _someObj.SomeMethod();
            });
        await t; //wait here, without blocking...
    }
    catch (Exception ex)
    {
        string errMsg = ex.Message + Environment.NewLine;
        errMsg += "some unhandled error occurred in SomeMethod";
        Log(errMsg);

        return; //<-- bypass below code on error...
    }

    //other code below... does not execute...
    DoSomethingElse();

}

备选方案 2:

private async void BtnClickEvent(object sender, RoutedEventArgs e)
{

    bool errOccurred = false;

    Task t = Task.Run(() =>
        {
            try
            {
                _someObj.SomeMethod();
            }
            catch (Exception ex)
            {
                string errMsg = ex.Message + Environment.NewLine;
                errMsg += "some unhandled error occurred in SomeMethod";
                Log(errMsg);

                errOccurred = true;

            }//end-Catch
        });
    await t; //wait here, without blocking...
    if (errOccurred) return; //<-- bypass below code on error...

    //other code below... does not execute...
    DoSomethingElse();  

}

最佳答案

更好的选择是将部分代码重构为一个单独的方法,该方法返回一个指示是否继续的 bool 值。

private async void BtnClickEvent(object sender, RoutedEventArgs e)
{
    bool success = await SomeMethodAsync();
    if (!success)
    {
        return;
    }

    //other code below... does not execute...
    DoSomethingElse();
}

private async Task<bool> SomeMethodAsync()
{
    try
    {
        await Task.Run(() => _someObj.SomeMethod());
        return true;
    }
    catch (Exception ex)
    {
        string errMsg = string.Format("{0} {1}some unhandled error occurred in SomeMethod",
        ex.Message, Environment.NewLine);
        Log(errMsg);          

        return false;
    }
}

关于c# - 使用 .NET 任务并行库捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32600134/

相关文章:

c# - 调试 Windows 服务

c# - 似乎无法通过 ASP.Net Core 连接到 SQL Server(一直返回空值)

java - 具有包含 HTML 代码的 JLabel 节点的 JTree 在展开节点时抛出异常

javascript - 有没有办法从箭头函数中捕获并返回 firebase 错误?

postgresql - 错误: invalid input syntax for type numeric: “N/A” … nice but which column?

linux - 用汇编语言访问 errno.h

c# - 在 C# 中发送消息

c# - 当字符串达到特定长度时删除字符串中的字符

Javascript onclick,抛出无法捕获的异常

android - 如果子 Activity 崩溃,则返回父 Activity