0

Im getting an error message when i try this:

Task.Factory
    .StartNew(() => _model.GetItems(node).Select(n => n))
    .ContinueWith(t =>
    {
        if (t.Result != null)
        {
            ObservableCollection<ItemValue> children = new ObservableCollection<ItemValue>(t.Result);                                
            //fill some control
        }
    }, TaskScheduler.FromCurrentSynchronizationContext());

Error

Must create dependencysource on same thread as the dependencyobject

But if i try this code:

Task.Factory
    .StartNew(() => _model.GetItems(node).Select(n => n))
    .ContinueWith(t =>
    {
        if (t.Result != null)
        {
            ObservableCollection<ItemValue> children = _model.GetItems(node);                                
            //fill some control
        }
    }, TaskScheduler.FromCurrentSynchronizationContext());

It's ok, no errors.

What am I doing wrong?

I want to fill collection in an other thread.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • possible duplicate of [Adding to an observable collection with alternate thread](http://stackoverflow.com/questions/7488358/adding-to-an-observable-collection-with-alternate-thread) – Nick Udell Jul 21 '14 at 10:17

1 Answers1

0

To force thread to change properties of UI elements that were created in other threads, you must use Dispatcher property of any UI element: http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherobject.dispatcher(v=vs.110).aspx

You can write simply:

Task.Factory.StartNew(async () =>
                {
                    ObservableCollection<ItemValue> children = new ObservableCollection<ItemValue>(await _model.Dispatcher.InvokeAsync<IEnumerable<ItemValue>>(() => _model.GetItems(node)));
                    // fill some control
                });
vdrake6
  • 111
  • 1
  • 10