Better way to show error messages in async methods

前端 未结 2 1413
鱼传尺愫
鱼传尺愫 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 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

提交回复
热议问题