0

I am starting a Window from a different application. Whenever I start the Window, it is done from a different thread. The first time I start the Window, everything works fine. Every later attempt fails with the error: The calling thread cannot access this object because a different thread owns it.

I used to assign the DataContext in the Xaml like this:

<UserControl.DataContext>
    <viewModels:MyViewModel/>
</UserControl.DataContext>

The error stopped, when I changed it to assign the ViewModel from the code behind like this:

public MyView() {
    InitializeComponent();
    DataContext = new MyViewModel();
}

According to an answer at MSDN these two approaches should be equivalent.

Why do I get different results? Is there a way to make my first approach work (as I would prefer it)?

Edit:

The control is initialized in another Xaml:

<userControls:MyView Grid.Column="2" x:Name="MyView" Grid.ColumnSpan="1" ></userControls:MyView>

The window itself is started using

AutoResetEvent are = new AutoResetEvent(false);
Thread thread = new Thread(() => {
    MyMainWindow form = new MyMainWindow(someObject);
    form.Closed += (sender2, e2) => {
        Dispatcher.CurrentDispatcher.InvokeShutdown();
        are.Set();
    };
    form.Show();
    Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
are.WaitOne();

Edit 2:

After some debugging I found the root cause. I was using a custom implementation of a messaging system based on the Prism Event Aggregator. When MyMainWindow was closed, I didn't clear all the subscriptions.

MartinThé
  • 706
  • 7
  • 19
  • 5
    To quote: *"Whenever I start the Window, it is done from a different thread."* and the error: *"The calling thread cannot access this object because a different thread owns it"*. It seems to be **quite clear** what the issue is here. Create your `MyView` on the **UI Thread**, [here's how](http://stackoverflow.com/questions/9602567/how-to-update-ui-from-another-thread-running-in-another-class). – Mike Eason May 10 '16 at 07:11
  • Show us how you create your view – Tomtom May 10 '16 at 11:52
  • @MikeEason Thanks for your suggestion. I realize that the threading is to blame for the error, yet I find it puzzling that one method works, while they other one doesn't even though they should be equivalent. – MartinThé May 10 '16 at 12:40
  • @Tomtom I added the information you asked for. – MartinThé May 10 '16 at 12:41
  • *"The window itself is started using"* wat –  May 10 '16 at 17:11
  • There is almost **NEVER** a case where you need to handle threads yourself. This isn't C++. With the TPL you get all you need to easily handle async operations or background work and with await/async you can even write your code in an sync manner. As for the reason, UI objects can only be created and modified from the UI Thread, nothing else. – Tseng May 11 '16 at 09:27

0 Answers0