Why compiler does not allow using await inside catch block

前端 未结 1 512
[愿得一人]
[愿得一人] 2021-02-19 07:50

Let say I have an async method:

public async Task Do()
{
    await Task.Delay(1000);
}

Another method is trying to call Do method

相关标签:
1条回答
  • 2021-02-19 08:32

    Update

    This will be supported in C# 6. It turned out that it wasn't fundamentally impossible, and the team worked out how to do so without going mad in the implementation :)

    Original answer

    I strongly suspect it's the same reasoning that prevents yield return from being used in a catch block.

    In particular:

    First off, we still have the problem that it is illegal to "goto" into the middle of the handler of a try-protected region. The only way to enter a catch block is via the "non-local goto" that is catching an exception. So once you yielded out of the catch block, the next time MoveNext was called, we’d have no way to get back into the catch block where we left off.

    Second, the exception that was thrown and caught is an intrinsic part of the execution of the catch block because it can be re-thrown using the "empty throw" syntax. We have no way of preserving that state across calls to MoveNext.

    Replace "yield" with "await" there, and I think you'll have your answer.

    It feels like it would be an odd thing to want to do in most cases, and you should usually be able to rewrite your code fairly easily to await after the catch block - unless you were trying to await something and then throw, of course. In that case it would be a bit of a pain, I admit...

    0 讨论(0)
提交回复
热议问题