首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#异步等待(尝试/)捕获在.NET 6中失败

C#异步等待(尝试/)捕获在.NET 6中失败
EN

Stack Overflow用户
提问于 2022-01-29 16:41:55
回答 1查看 997关注 0票数 2

以下代码按照预期的方式工作( .NET 4.8项目的WPF .NET项目的代码隐藏)。

代码语言:javascript
复制
    private async Task DeleteAsync()
    {
        try
        {
            await ViewModel.DeleteAsync(GetSelectedItems());
        }
        catch (Exception ex)
        {
            var doCatch = ex is ValidationException
                || ex is ExpectedInfoException
                || ex is ExpectedDbException;
            if (doCatch)
                ExeptionHelper.HandleException(ex, AppConstants.ApplicationName);
            else
                throw;
        }
    }

下面的模拟实验并不总是捕捉到.NET 6.0项目中的异常,请参阅内联注释。我尝试的最低限度的可复制的复制样本还没有完成,但希望有人已经有了一个有教养的猜测的原因?

代码语言:javascript
复制
        private async void DeleteListAsync()
        {
            var list = ViewModel.GetSelectedItems(
                dataGrid.SelectedItems.OfType<ActorModel>().ToList());
            try
            {
                await ViewModel.DeleteListAsync(list);
            }
            catch (Exception ex) when (
                ex is ValidationException
                || ex is ExpectedInfoException
                || ex is ExpectedDbException)
            {
                /* this part does run as expected when() one of those three 
                 * custom MyNamespace.Exceptions gets thrown in the previous `try` block.
                 * But unexpectedly *not when thrown inside the nested step-into code of 
                 * ViewModel.DeleteListAsync() */
                ApplicationHelper.HandleException(ex, Intl.LocalizedConstants.AppName);
            }
            catch
            {
                /* this part does run as expected when a `new InvalidOperationException("Test")`
                 * or `NotImplementedException()` gets thrown directly in the `try`block.
                 * Also when thrown inside the nested step-into code of 
                 * ViewModel.DeleteListAsync() */
                throw;
            }
        }

解决:很久之后,在有用的评论的帮助下,我实际上在嵌套代码的一个隐蔽而黑暗的角落找到了一个缺失的等待语句,就像@Charlieface说的那样,非常感谢大家!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-31 02:13:49

显然,您的代码中缺少一个await,这将导致异常被包装在AggregateException中。

await所做的事情之一,以及设置状态机制,是打开包含在运行Task期间抛出的任何异常的AggregateExceptions。因此,如果您希望捕获和处理特定的异常类型,则应该一直使用await

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70907575

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档