c# - 为什么VS2017说await是一个未知关键字?

标签 c# visual-studio-2017 task-parallel-library

    internal /*async*/ void RunAsync()
    {
        var tasks = ...;
        await Task.WhenAll(tasks);
    }

在上面的示例中,IDE 通知我“''await 运算符只能在异步方法中使用”。它为我提供了修复方法,使我的方法签名async voidasync Task

    internal /*async*/ void RunAsync()
    {
        var tasks = ...;
        var t = Task.WhenAll(tasks);
        await t;
    }

在第二个示例中,它给出错误“找不到类型或命名空间等待”...await 未将颜色编码为语言关键字,并且 IDE 没有为我提供自动修复.

这是 VS 的错误吗?

最佳答案

在这两种情况下,代码都是无效的 C# 代码。因此,编译器/IDE 必须尽力找出您正在尝试执行的操作,并为您提供适当的错误消息。

In the above example, the IDE informs me "the ''await operator can only be used within an async method". It offers me fixes to make my method signature async void or async Task

VS 正在解析代码,并且非常确定此处的 await 旨在作为 await 运算符。该代码不是有效的 C#,但这就是您想要做的。因此,它为您提供了一个有用的建议,即您必须使用 async 关键字才能使 await 成为关键字。

In the second example, it gives the error "the type or namespace await cannot be found"... await is not color-coded as a language keyword and the IDE offers me no automatic fixes.

VS正在解析代码,不确定这里的awaitawait运算符还是类型。对于编译器来说,await t; 看起来很像int t;

Is this a VS bug?

这不是一个错误,因为代码一开始就是无效的 C#。但在第二种情况下,您可以要求提供更好的错误消息,并且 C# 编译器团队可能会也可能不会决定值得这样做,而不是开发其他功能。

对于上下文,请注意 await is a contextual keyword 。如果存在 async 关键字,它只是一个关键字。 await并不总是一个关键字,如果 VS 始终将其视为关键字,那将是一个错误。具体来说,在此处的两个代码示例中,await 不是关键字。 VS 在第一个示例中不遗余力地进行额外的后备解析,以检测开发人员打算使用 await 关键字的常见场景。

关于c# - 为什么VS2017说await是一个未知关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60737522/

相关文章:

c# - 一起运行两个 parallel.foreach()

c# - 如何在 VSPackage 中获取 IVsExpansionClient 的实例?

visual-studio - 如何在 Visual Studio 的特定文件夹中运行单个测试或所有测试?

c# - 如何在 VS2017 中为 Entity Framework 添加 Oracle 提供程序?

c++ - Visual Studio 2017 c++ win32 控制台项目模板

c# - 如何使用任务并行库管理任务列表

system.reactive - Reactive Framework、PLINQ、TPL 和并行扩展如何相互关联?

c# - '.' 附近的语法不正确。 - C#

c# - 将数组从 C# 返回到 javascript 的最佳(简单且清晰)方法是什么

c# - 使用客户端 key 的 Azure 和 Microsoft Graph : Access denied accessing inbox,