我想这类事情一般不应该做,但我想了解为什么这段代码会阻止UI,而不是从await taskMain:
using System.Diagnostics;
namespace TasksTest
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void buttonTest1_Click(object sender, EventArgs e)
{
try
{
DoTest1Async().Wait();
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
private static async Task DoTest1Async()
{
Task taskMain = Task.Run(() => {
Debug.WriteLine("Test #1 completed");
});
await taskMain;
}
}
}
如果我没有使用Wait(),而是使用了aWait,它可以完美地工作.我想知道是否有一种方法可以同步执行DoTest1Async而不会阻止UI.
-编辑
在理解了调用等待方法会阻塞UI线程并且不允许已完成的任务taskMain返回到UI线程上下文并继续执行之后...为什么下一个代码替代方案不以同样的方式阻止用户界面线程?我仍然不明白,如果我在另一个线程中启动代码,而UI线程在线程中被阻塞,为什么taskMain可以返回.Join,但它不能在简单的Wait()指令中返回.这听起来很奇怪.也许Wait方法的实现需要修改...?
private void buttonTest1_Click(object sender, EventArgs e)
{
Thread thread = new(() =>
{
try
{
DoTest1Async().Wait();
Debug.WriteLine("Unblocked!!");
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
});
thread.Start();
thread.Join();
Debug.WriteLine("Thread Finished!");
}