0

I have a button that opens a second window but the second window has a bit of processing to do before displaying. Rather than have the initial window die until the second screen appears I would like to inform the user that processing is happening. My thoughts on how to do this;

1) Call the second window in a second thread, have the UI in the first window display "Loading" etc, once the second window has completed pass an indicator to the first window to stop displaying "Loading".

I have read a bit about dispatcher & beginInvoke but still struggling a bit to get this to work. I was trying this out and in my Window1 initializer I have a thread.Sleep just to test out that my mainWindow is still working but it is not. Any help would be greatly appreciated.

1
  • I think you need to grab a book about WPF and C# programming. I get the impression there is far too much you don't know that you need to know. Commented Aug 4, 2017 at 10:37

1 Answer 1

3

You cannot open windows and do other UI tasks on worker threads. All these activities have to be performed on the main thread. You can do that by invoking on the dispatcher from the background thread:

private void worker_DoWork(object sender, DoWorkEventArgs e) { // First do the work Thread.Sleep(...); // Then show the window Application.Current.Dispatcher.Invoke(() => window1.Show()); } 

Using this simple approach where you grab the dispatcher in event handlers can quickly get out of hand and as your application grows you might want to switch to a more strict programming model using for instance a MVVM framework of sorts.

From a UX perspective it might be better to show the second window immediately and then display a progress bar or spinner indicating that work is being performed. Then when the work is done hide this indicator and show the result of the work. The principle of updating the UI from the background thread using the dispatcher still applies.

Sign up to request clarification or add additional context in comments.

1 Comment

I actually really appreciate the suggestion of "loading" in the second window, that's what I will do. Also you have clarified the dispatcher / worker distinction. Thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.