Reputation: 525
I am new to the threading concepts.
I have checked the questions with the same content but couldn't relate to my current problem, which is
I have a text box in the UI bonded to GridSize in MyViewModel.cs When the grid size changes there is a heavy calculations updating the UI components which make the application to freeze, so I tried to use TPL Task.Factory.StartNew().
That gives me error "the calling thread cannot access this object because a different thread owns"
I am using MEF to import the ViewModel.
Xaml.cs file
[Import]
public MyViewModel ViewModel
{
get { return DataContext as MyViewModel; }
set
{
if (DataContext is MyViewModel)
ViewModel.OnModelUpdated -= ModelUpdatedEvent;
DataContext = value;
if (DataContext is MyViewModel)
{
ViewModel.OnModelUpdated += ModelUpdatedEvent;
}
}
}
private void ModelUpdatedEvent(object sender, EventArgs e)
{
// code to update the UI.
}
MyViewModel.cs
public double GridSize
{
get { return _settings.GridSize; }
set
{
_settings.GridSize = value;
ModelUpdatedEvent();
}
}
public event EventHandler OnModelUpdated;
public void ModelUpdatedEvent()
{
EventHandler eventModelUpdated = OnModelUpdated;
if (eventModelUpdated != null)
{
Task.Factory.StartNew(()=> eventModelUpdated.Invoke(this, EventArgs.Empty));
}
}
Any help is much appreciated.
Upvotes: 1
Views: 2484
Reputation: 21261
WPF visual objects can only be manipulated by the thread with which they were created. The TPL executes things in parallel by using other threads.
You can marshal the result of your calculation back to the correct thread using Dispatcher.BeginInvoke()
:
Application.Current.Dispatcher.BeginInvoke(new Action(() => this.GridSize = calculatedGridSize));
Per your comment. If your blocking calculations are in the view, then you still need to offload those calculations to another thread in the code behind. You need to split out the actual calculations from the code that actually touches the view items. Once the calculations are done then you need to marshal any calls to visual items in the manner above.
Upvotes: 7