Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Run WPF window in separate thread and await for it to close

I need to run a new WPF window in parallel with the main one on button click. Another window should not open until the previous was closed. I found this answer to run a new window in separate thread and this answer to await the Closed event.

I tried to combine them using Task but encountered the following problem. A new window opens independently from the main one, but await task does not pause the function execution. In addition, when I close the main window, a new window remains.

Can anyone suggest me how to solve the problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

bool signal = false; 

private async void butHelp1_Click(object sender, RoutedEventArgs e)
{
    // Check the global signal variable to not let a new window open
    if (signal) return;

    signal = true;

    Task task = Task.Run(() =>
    {
        Thread thread = new(() =>
        {
            NewWindow window = new();
            window.ShowDialog();

            System.Windows.Threading.Dispatcher.Run();
        });

        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    });

    // This line does not pause the function execution
    await task;

    signal = false;
}

>Solution :

If I understand correctly what you need, then look at this implementation:

        private bool isClosedNewWindow = false;
        private NewWindow? newWindow;

        private void butHelp1_Click(object sender, RoutedEventArgs e)
        {
            if (isClosedNewWindow)
            {
                if (newWindow?.WindowState == WindowState.Minimized)
                    newWindow.WindowState = WindowState.Normal;
            }
            else
            {
                isClosedNewWindow = true;

                newWindow = new NewWindow();
                newWindow.Closed += delegate { isClosedNewWindow = false; };
                newWindow.Show();
            }
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading