为什么编译器不允许使用等待里面catch块 [英] Why compiler does not allow using await inside catch block

查看:99
本文介绍了为什么编译器不允许使用等待里面catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让说,我有一个异步方法:

Let say I have an async method:

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

另一种方法是试图调用不要 Catch中的方法

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?

推荐答案

更新

这将在C#中的支持6.原来,这是没有从根本不可能的,团队制定了如何做到这一点,而不在实施要疯了:)

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

原来的答复

我强烈怀疑这是相同的<一个href=\"http://blogs.msdn.com/b/ericlippert/archive/2009/07/20/iterator-blocks-part-four-why-no-yield-in-catch.aspx\"相对=nofollow>推理prevents 收益回报率被使用。>

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

在特定的:

首先,我们仍然有,这是违法的转到成一试保护区的处理程序中间的问题。进入catch块的唯一方法是通过非局部的goto,即捕获异常。所以一旦你产生了catch块,下一次的MoveNext被调用的,我们就没有办法重新回到我们离开的catch块。

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.

其次,被抛出和捕捉到的异常是在catch块的执行固有的一部分,因为它可以使用空throw语法重新抛出。我们没有pserving通过调用该州对MoveNext方法$ P $的。

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.

这感觉就像那将​​是一件奇怪的事来的希望的在大多数情况下做的,你应该的一般的能够重写code很容易在块之后等待 - 除非你试图等待的东西,然后扔,当然。在这种情况下,这将是一个有点痛,我承认...

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...

这篇关于为什么编译器不允许使用等待里面catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆