简体   繁体   English

Async / Await可在Windows Form应用程序中使用,但不应

[英]Async/Await works in Windows Form application, but it shouldn't

Based on MSDN article following code shouldn't work in Windows Forms application and I'm pretty much certain, that it didn't work in past, but recently I've discovered, that in .NET framework 4.7.02558 it works. 根据MSDN文章,以下代码不应在Windows Forms应用程序中运行,并且我可以肯定,它在过去不起作用,但是最近我发现,在.NET Framework 4.7.02558中它可以工作。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void Test()
    {
        Console.WriteLine("One");

        var d = DelayAsync();

        Console.WriteLine("Three");

        d.Wait();
        Console.WriteLine("Five");
    }

    private async Task DelayAsync()
    {
        Console.WriteLine("Two");

        await Task.Delay(1000);
        Console.WriteLine("Four");
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        Test();
    }
}

Did I miss some a release log, or is something wrong (I mean right from user's perspective)? 我错过了一些发布日志,还是出了点问题(从用户的角度来看我是对的)?

Edit: An application should freeze after returning from awaited code because in Windows Forms is used CurrentContextSheduller. 编辑:从等待的代码返回后,应用程序应该冻结,因为在Windows窗体中使用了CurrentContextSheduller。

Testing on 4.7.1 I get the following results: 在4.7.1上进行测试,我得到以下结果:

One
Two
Three

Four , and Five never get displayed. FourFive永远不会显示。 It seems to be "not-working as intended" for me, as execution of await Task.Delay(1000); 对我来说,这似乎“没有按预期工作”,因为执行了await Task.Delay(1000); is blocking. 正在阻止。

Discovered. 发现。 The problem was caused by ReSharper Build & Run. 该问题是由ReSharper Build&Run引起的。 For some reason, the build wasn't done and switching from ReSharper Build to Visual Studio build program behaves "correctly". 由于某些原因,构建未完成,因此从ReSharper Build切换到Visual Studio生成程序的行为“正确”。 Latest build was done with .ConfigureAway(false) , so that's a root cause of why it worked and shouldn't. 最新的构建是使用.ConfigureAway(false) ,因此这是它为什么起作用以及不应起作用的根本原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM