Better way to show error messages in async methods

前端 未结 2 1434
鱼传尺愫
鱼传尺愫 2021-02-19 21:01

The fact that we can\'t use the await keyword in catch blocks makes it quite awkward to show error messages from async methods in WinRT, since the

相关标签:
2条回答
  • 2021-02-19 21:47

    C# 6 now supports await in catch and finally, so the code can be written the way I wanted it; a workaround is no longer needed.

    0 讨论(0)
  • 2021-02-19 22:02

    you already have that functionality in TPL

            await Task.Run(async () =>
            {
                // Some code that can throw an exception
                ...
            }).ContinueWith(async (a) =>
            {
                if (a.IsFaulted)
                {
                    var dialog = new MessageDialog("Something went wrong!\nError: "
                               + a.Exception.Message);
                    await dialog.ShowAsync();
                }
                else
                {
                    var dialog2 = new MessageDialog("Everything is OK: " + a.Result);
                    await dialog2.ShowAsync();
                }
            }).Unwrap();
    

    In this machine I don't have Windows 8 so I tested in Windows 7 but I think is the same. *Edit as stated in the comments its needed .Unwrap(); in the end for the await to work

    0 讨论(0)
提交回复
热议问题