Rohit
Rohit

Reputation: 10236

WPF threading error(Invalid Operation Exception was handled)

I am creating WPF Project and I have two screen

1)Loading Screen

2)MainWindow

My code is as follows from Loading screen

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        loadingThread = new Thread(load);
        loadingThread.SetApartmentState(ApartmentState.STA);
        loadingThread.Start();

    }

   private void load()
    {
        Thread.Sleep(1000);
        this.Dispatcher.Invoke(showDelegate, "Loading UI...");
        Thread.Sleep(2000);
        //do some loading work
        this.Dispatcher.Invoke(hideDelegate);

        Thread.Sleep(2000);
        this.Dispatcher.Invoke(DispatcherPriority.Normal,
        (Action)delegate() { this.CLose(); });

        MainWindow Mw = new MainWindow();//Gives me the error
        Mw.ShowDialog();
    }

When I call my Mainwindow screen I get error "The Application object is being shut down".I beleive since the thread is being closed I am getting the error , can anyone tell me what would be the other possible ways to call my main window

Thank You All

Upvotes: 2

Views: 2255

Answers (1)

Silvermind
Silvermind

Reputation: 5944

You're closing the last window which invokes the shutdown command for the application. Create and open the new window before you close 'this' window:
You could change this:

this.Dispatcher.Invoke(DispatcherPriority.Normal,
    (Action)delegate() { this.Close(); });

to this:

this.Dispatcher.Invoke(DispatcherPriority.Normal,
(Action)delegate() 
{
    MainWindow Mw = new MainWindow();
    // Mw.ShowDialog(); I changed this line because it cannot be a dialog here.
    Mw.Show();
    this.Close();
});

Upvotes: 1

Related Questions