C# Async/Await在Windows窗体应用程序中工作,但它不应该';T
基于以下代码,Windows窗体应用程序中不应使用这些代码,而且我非常确定,它在过去不可用,但最近我发现,在.NET framework 4.7.02558中,它可以使用C# Async/Await在Windows窗体应用程序中工作,但它不应该';T,c#,.net,winforms,asynchronous,C#,.net,Winforms,Asynchronous,基于以下代码,Windows窗体应用程序中不应使用这些代码,而且我非常确定,它在过去不可用,但最近我发现,在.NET framework 4.7.02558中,它可以使用 public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void Test() { Console.WriteLine("One");
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();
}
}
我是否错过了一些发布日志,或者是出了什么问题(我的意思是从用户的角度看是正确的)
编辑:应用程序在从等待的代码返回后应该冻结,因为在Windows窗体中使用的是CurrentContextSheduler。在4.7.1上测试我得到以下结果: 一个
两个
三
4个
和5个
永远不会显示。对我来说,它似乎“没有按预期工作”,因为的执行等待任务。延迟(1000)代码>被阻止。被发现。该问题是由ReSharper生成和运行引起的。由于某些原因,构建没有完成,并且从ReSharper构建切换到Visual Studio构建程序的行为“正确”。
最新的构建是使用.ConfigureAway(false)
完成的,因此这是它工作和不应该工作的根本原因。Visual Studio 2017 Professional,Console.WriteLine()
输出到Visual Studio中的˙Output˙窗口。好吧,它在调试和非调试模式下(输出Console.WriteLine)对我来说(如预期的那样)是死锁的()
仅在调试模式下可见).I当前没有4.7,因此无法复制它。VisualStudio 2017与.net 4.7兼容冻结。@SebastianBusek应用程序将冻结,因为只有一个UI线程,而不是因为CurrentContextSheduler
。当前同步上下文是每个等待的将返回/重新创建的内容,具有不同的含义对于不同类型的应用程序。对于Winforms/WPF,这是单个UI线程。无论如何,在4.7.1上没有重新编程。应用程序冻结。@SebastianBusek您是如何确定应用程序没有冻结的?您是否能够单击按钮两次?如果您在var d=DelayAsync();
中更改var d=Task.Run(async()=>wait DelayAsync());
您会让它再次工作:)