Async Task.Run with MVVM

I played with the new asynchronous CTP and MVVM patterns. I converted my old program, which used a background worker and reported progress in updating the collection in my model. I converted it to something like that

TaskEx.Run(async () =>
{
  while (true)
  {
    // update ObservableCollection here
  }
  await TaskEx.Delay(500);
});

In my opinion, I am attached to my view model, which provides this observable collection. However, when my collection updates, I get the following exception

This type of CollectionView does not support changes to the SourceCollection from a stream other than the Dispatcher stream.

I'm not sure what the correct way to pull back into the UI thread when this is done.

+5
source share
3 answers

async Task.Run() , . , .

:

Action f = async () =>
{
    while (true)
    {
        // modify the observable collection here
        await Task.Delay(500);
    }
};

, , :

f();

, . . 500 ( , ) .

, :

Task.Run(addNames);

. , async , ( ). , . ThreadPool ( Task.Run()) . .

SynchronizationContext, .

+5

ObservableCollection , WPF.

, ObservableCollection .

ObservableCollection :

private async void LoadItems()
{
    Task<List<MyItem>> getItemsTask = Task.Factory.StartNew(GetItems);

    foreach(MyItem item in await getItemsTask)
        MyCollection.Add(item);
}

private List<MyItem> GetItems()
{
    // Make database call to get items
}
+3

All Articles