问题
Let say I have an async method:
public async Task Do()
{
await Task.Delay(1000);
}
Another method is trying to call Do
method inside catch
block
public async Task DoMore()
{
try
{
}
catch (Exception)
{
await Do(); //compiled error.
}
}
But this way, the compiler does not allow using await
inside catch
, is there any reason behind the scene why we could not use it that way?
回答1:
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...
来源:https://stackoverflow.com/questions/12879926/why-compiler-does-not-allow-using-await-inside-catch-block