使用异步任务处理多个对话框 windows
Handling multiple dialog windows with async tasks
在我的主要 WinForm 应用程序 window 中,我想同时打开多个无模式对话框。当所有对话框 windows 打开时,我将引发一些事件,并且各个打开的对话框上的事件处理程序应该对这些事件采取必要的操作。由于用户一直想访问主窗体,我无法将这些 windows 作为模态对话框打开。
我写了下面的代码。
使用此代码,对话框 windows 打开但它们也立即关闭。代码有什么问题?为什么 windows 不保持开放?
private async void buttonOpenWindows_Click(object sender, EventArgs e)
{
Task[] tasks = new Task[]
{
Task.Factory.StartNew(CreateWindow),
Task.Factory.StartNew(CreateWindow),
Task.Factory.StartNew(CreateWindow),
Task.Factory.StartNew(CreateWindow)
};
await Task.WhenAll(tasks);
// Raise necessary events when all windows are loaded.
}
private async Task CreateWindow()
{
// A refernce to main form is passed to the Window because all Windows will be subsribing to some events raised by the main form.
var window = new Window1(this);
window.Show();
}
发生了什么:
private async Task CreateWindow()
{
// A refernce to main form is passed to the Window because all Windows will be subsribing to some events raised by the main form.
var window = new Window1(this);
window.Show();
}
这将创建一个新的 window,由系统中的第一个可用线程拥有。由于 运行 没有更多的阻塞代码,Task
成功完成,因此 Window
是 closed/disposed。
如果想让Window
继续打开,需要在主线程中打开。
不过,我不确定以 async
方式打开 Windows
会带来什么好处。
在我的主要 WinForm 应用程序 window 中,我想同时打开多个无模式对话框。当所有对话框 windows 打开时,我将引发一些事件,并且各个打开的对话框上的事件处理程序应该对这些事件采取必要的操作。由于用户一直想访问主窗体,我无法将这些 windows 作为模态对话框打开。
我写了下面的代码。
使用此代码,对话框 windows 打开但它们也立即关闭。代码有什么问题?为什么 windows 不保持开放?
private async void buttonOpenWindows_Click(object sender, EventArgs e)
{
Task[] tasks = new Task[]
{
Task.Factory.StartNew(CreateWindow),
Task.Factory.StartNew(CreateWindow),
Task.Factory.StartNew(CreateWindow),
Task.Factory.StartNew(CreateWindow)
};
await Task.WhenAll(tasks);
// Raise necessary events when all windows are loaded.
}
private async Task CreateWindow()
{
// A refernce to main form is passed to the Window because all Windows will be subsribing to some events raised by the main form.
var window = new Window1(this);
window.Show();
}
发生了什么:
private async Task CreateWindow()
{
// A refernce to main form is passed to the Window because all Windows will be subsribing to some events raised by the main form.
var window = new Window1(this);
window.Show();
}
这将创建一个新的 window,由系统中的第一个可用线程拥有。由于 运行 没有更多的阻塞代码,Task
成功完成,因此 Window
是 closed/disposed。
如果想让Window
继续打开,需要在主线程中打开。
不过,我不确定以 async
方式打开 Windows
会带来什么好处。