当我尝试这个时,我得到一个错误消息:
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());
误差必须在与dependencyobject相同的线程上创建dependencysource
但是如果我尝试这个代码:
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());
没问题,没有错误。
我做错了什么?
我想在另一个线程中填充collection
要强制线程更改在其他线程中创建的UI元素的属性,必须使用任何UI元素的Dispatcher属性:http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherobject.dispatcher (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
});