1

In my WPF including Caliburn.Micro application, I want to show a new window to the user. This works fine for all the windows but for one. It throws an exception stating

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

this is how I call the Window Manager

WindowManager.ShowWindow(new DatabaseCredentialsViewModel(EventAggregator, WindowManager,
                    SettingsManager));

Besides, I also tried to 'create a new Window Manager' by new WindowManager().ShowWindow(...);. However, none of the above work. What is different from the other windows?

I started a new thread for the work in the background in OnViewLoaded, from which I want to show a new window. The reason why I started a new thread in the first place is that by default, the GUI thread is the main thread and thus, if I don't start a new thread, the GUI isn't properly loaded until the code is executed (and so on).

Edit I: I investigated the problem and found out that it is not the Window Manager causing the trouble at this point, but perhaps new DatabaseCredentialsViewModel, as I created a completely new Window Manager (a new instance of the original class) and it would still throw the same error.

Edit II: I tried this. However, the exact error persists.

Dispatcher.CurrentDispatcher.BeginInvoke((Action) (() =>
            {
                WindowManager.ShowWindow(new DatabaseCredentialsViewModel(EventAggregator, WindowManager, SettingsManager));
            }));
Çan
  • 125
  • 1
  • 2
  • 11
  • Have you tried using `Application.Current.Dispatcher` instead of `Dispatcher.CurrentDispatcher`? – Doom5 Jan 28 '17 at 01:55
  • I did exactly this the other day and now it's working (despite not having seen your answer at the time). But it was right. My code posted works great when changing to Application.Current.Dispatcher. – Çan Jan 28 '17 at 09:49

1 Answers1

-1

WPF apps are single threaded applications, you can't directly modify GUI elements from another thread. You can use Dispatcher for this (google Dispatcher.BeginInvoke, or see example), or BackgroundWorker, or, preferably, async/await (see this).

Community
  • 1
  • 1
mechanic
  • 761
  • 6
  • 11