Ted
Ted

Reputation: 1760

Show modal dialog in parallel thread

I need to show window with spinner, during processing some action. This Window should be model, so I am using ShowDialog() method:

 void ShowDlg() {
        Thread WindowThread = new Thread(() =>
    {
        SpinnerWindow spinnerWindow = new SpinnerWindow();
        spinnerWindow.ShowDialog();
        System.Windows.Threading.Dispatcher.Run();
    });
        WindowThread.SetApartmentState(ApartmentState.STA);
        WindowThread.Start();
 }

Then after some process is done, I am trying to close this modal window:

                WindowThread.Interrupt();
            if (!WindowThread.Join(2000))
            { 
                WindowThread.Abort();
            }

and everything works well, until I try to call ShowDlg() second time. I am getting next exception:

The calling thread cannot access this object because a different thread owns it.

What I am doing wrong, maybe incorrect close of created thread?

Upvotes: 0

Views: 1634

Answers (1)

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

You are probably calling the ShowDialog from within another thread again. When that's the case you should invoke your main form like this:

mainForm.Invoke(spinnerWindow.ShowDialog());

Upvotes: 2

Related Questions