Learner
Learner

Reputation: 4751

Handling multiple dialog windows with async tasks

From my main WinForm application window, I want to simultaneously open multiple modeless dialogs. When all dialog windows are opened, I will raise some events and the event handlers on individual open dialogs are supposed to take necessary actions on those events. Since user wants access to the main form all the time, I cannot open these windows as modal dialogs.

I have written following code.

With this code, the dialog windows are opened but they are immediately closed too. What's wrong with the code? Why windows don't remain open?

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();
}

Upvotes: 0

Views: 468

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32062

What is happening:

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();
}

This creates a new window, owned by the first available thread in the system. As there is no more blocking code to run, the Task finishes successfully, and so the Window is closed/disposed.

If you want the Window to continue to be opened, you need to open it in your main thread.

Not sure what you are expecting to benefit from by opening the Windows in an async manner, though.

Upvotes: 4

Related Questions