0

当我尝试这个时,我收到一条错误消息:

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());

错误

必须在与依赖对象相同的线程上创建依赖源

但如果我尝试这段代码:

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());

没问题,没有错误。

我究竟做错了什么?

我想在另一个线程中填写集合。

4

1 回答 1

0

要强制线程更改在其他线程中创建的 UI 元素的属性,您必须使用任何 UI 元素的 Dispatcher属性:http: //msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherobject。调度程序(v=vs.110).aspx

你可以简单地写:

Task.Factory.StartNew(async () =>
                {
                    ObservableCollection<ItemValue> children = new ObservableCollection<ItemValue>(await _model.Dispatcher.InvokeAsync<IEnumerable<ItemValue>>(() => _model.GetItems(node)));
                    // fill some control
                });
于 2014-07-21T10:35:00.610 回答