I’m running Visual Studion 2010 (Net 4.0)
I’m creating a task that loads some values into an ObservableCollection and comes back to the UI after that. This is the code:
LoadValues = Task.Factory.StartNew<ObservableCollection<DataGridEntity>>(curDataLoader.LoadValuesTask);
ItemsList = LoadValues.Result;
this.DataContext = ItemsList;
This code snippet works fine! But with the .Result Property the UI-thread waits until the LoadValues task comes back.
So I want to do it that way:
LoadValues = Task.Factory.StartNew<ObservableCollection<DataGridEntity>>(curDataLoader.LoadValuesTask);
LoadValues.ContinueWith((FinishLoadDataToDataGrid1) =>
{
ItemsList = LoadValues.Result;
this.DataContext = ItemsList;
});
Very little difference. I used ContinueWith to prevent the UI thread from waiting.
But if I do it that way he tells me: “Calling thread cannot access object because different thread owns it” at “this.DataContext = ItemsList;”
Is it a timing problem? Does anyone have any ideas?
You need to use the TaskScheduler.FromCurrentSynchronizationContext() to run the ContinueWith on the UI thread.