微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 为什么在finally块中不允许等待?

为什么等待是不允许在最后的块?
public async void Fn()
{
    try
    {
    }
    finally
    {
        await Task.Delay(4000);
    }
}

知道有可能手动获取Awaiter

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

解决方法

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

Inside of a catch or finally block. You can use “await” inside of a
try block,regardless of whether it has associated catch or finally
blocks,but you can’t use it inside of the catch or finally blocks.
Doing so would disrupt the semantics of CLR exception handling.

这在C#6.0中显然不再是真的

取自:A C# 6.0 Language Preview

C# 6.0 does away with this deficiency,and Now allows await calls within both catch and finally blocks (they were already supported in try blocks)

原文地址:https://www.jb51.cc/csharp/96202.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐