【问题标题】:Why await is not allowed in a finally block?为什么在 finally 块中不允许等待?
【发布时间】:2015-07-05 08:16:36
【问题描述】:

为什么 await 不允许在 finally 块中?

public async void Fn()
{
    try
    {
    }
    finally
    {
        await Task.Delay(4000);
    }
}

知道可以手动获取Awaiter

public void Fn()
{
    try
    {
    }
    finally
    {
        var awaiter = Task.Delay(4000).GetAwaiter();
     }
}

【问题讨论】:

  • 您是否阅读过 Eric Lippert 关于 finally 块中没有收益的博客文章?许多相同的点适用:blogs.msdn.com/b/ericlippert/archive/2009/07/16/…
  • 这里只是猜测:可能是因为 try...finally 和 await 发生在不同的编译器步骤中,它们的组合不好?

标签: c# async-await c#-5.0


【解决方案1】:

取自:Where can’t I use “await”?

在 catch 或 finally 块内。您可以在 a 中使用“await” try 块,不管它是否有关联的 catch 或 finally 块,但你不能在 catch 或 finally 块中使用它。 这样做会破坏 CLR 异常处理的语义。

这显然在 C# 6.0 中不再适用

取自:A C# 6.0 Language Preview

C# 6.0 消除了这个缺陷,现在允许在 catch 和 finally 块中调用 await(它们已经在 try 块中得到支持)

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 2023-04-11
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2011-01-01
    相关资源
    最近更新 更多