这是我尝试捕获错误的两种选择,它们似乎都做相同的事情..但是比另一种更可取,为什么?

替代项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();

}

Alt 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(boolean) 值。

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 Task Parallel Library捕获错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32600134/

10-10 06:10