You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7中await using搭配ClientBase时catch块异常问题问询

.NET 7 WCF客户端await using崩溃问题排查

我们使用VS2022生成了继承自System.ServiceModel.ClientBase(实现IAsyncDisposable接口)的.NET 7服务客户端,理论上该客户端可与await using语法配合使用,代码示例如下:

await using var client = new GeneratedClient(...);

try
{
    var response = await client.generatedRpc(...);
    ... do stuff
    return GetResult(response.someProperty);
}
catch (Exception ex)
    when (... some check of the message )
{
    throw new SpecificException(ex.Message, ex); // 使用await using时在此处崩溃
}

调试过程中发现:await client.generatedRpc(...)执行完全正常,response.someProperty也已正确赋值,但程序会跳至catch块的throw语句处崩溃。我们曾怀疑IL代码与.cs文件不同步,但清理项目后重新构建,问题仍然存在。如果将await using替换为using,则不会出现崩溃问题。

我们推测await using的语法糖编译后的逻辑如下:

var client = new GeneratedClient(...);
try
{
    try
    {
        var response = await client.GeneratedRpc(...);
        ... do stuff
        return GetResult(response.someProperty);
    }
    catch (Exception ex)
        when (... some check of the message )
    {
        throw new SpecificException(ex.Message, ex); // 在此处崩溃
    }
}
finally {
    await client.DisposeAsync();
}

其中await using会在finally块中执行await client.DisposeAsync();,而using则执行client.Dispose();。由于using可以正常运行,我们推测同步的Dispose()方法没有抛出异常,而异步的DisposeAsync()方法抛出了异常。

我们存在以下疑问:

  • 为何await using会崩溃而using不会?
  • 外层try-finally中DisposeAsync()的异常为何会进入内层try-catch?

内容的提问来源于stack exchange,提问作者Keith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:35:17