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.