Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

Why await is not allowed in a finally block?

Why await is not allowed in a finally block?

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

knowing that it is possible to get the Awaiter manually

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

Upvotes: 10

Views: 3860

Answers (1)

BlakeH
BlakeH

Reputation: 3484

Taken from: 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.

This is apparently no longer true in C# 6.0

Taken from: 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)

Upvotes: 13

Related Questions