我有问题,更新使用任务线程内绑定到一个ObservableCollection<T>
一个WPF的ListView(任务并行库)
我有一个小工具阅读Edifact文件,并显示每个段(线路的头三个字母)的计数。
与他们的计数包含段显示在列表框中的。
德恩我首先加载文件中的所有工作正常,我看到GUI上数的段。我PROGRAMM允许切换到另一个文件,如果我这样做(使用完全相同的代码),它除了具有以下不同failes。
这种类型的CollectionView不支持从一个线程从调度线程不同其SourceCollection变化。
这里是一个失败的代码
public class SegementLineCollection : ObservableCollection<SegmentLine>
{
public void IncrementCount(string Segment)
{
Segment = Segment.ToUpper();
SegmentLine line;
if (this.Select(x => x.SegmentName).Contains(Segment))
{
line = this.Where(x => x.SegmentName == Segment).FirstOrDefault();
}
else
{
line = new SegmentLine();
line.SegmentName = Segment;
this.Add(line); // <--- At this point comes the Exception
}
line.Count++;
}
}
这里是TPL呼叫我使用:
private string _FileName;
public string FileName
{
get
{
return _FileName;
}
set
{
_FileName = value;
OnPropertyChanged("FileName");
if (!String.IsNullOrEmpty(value))
new Task(() => StartFile()).Start();
}
}
有没有人对我有什么冲击吗?
------------Ëd I T ------------------
使用TaskScheduler.FromCurrentSynchronizationContext()或调度员提供的答案没有做的伎俩!
是否有可能加载新的改变时绑定的伎俩。
这里是我绑定使用,读者对象切换在视图模型和GUI的公告与实施INotifyPropertyChanged的
使用调度程序来访问集合:
if (Dispatcher.CurrentDispatcher.CheckAccess())
this.Add(...)
else
Dispatcher.CurrentDispatcher.Invoke(() => this.Add(...));
你需要调用IncrementCount GUI线程上。
随着TPL,你可以在你的任务或继续使用TaskScheduler.FromCurrentSynchroniztionContext()
。
var task = new Task<string>(() => { return "segment"; })
var task2 = task.ContinueWith(t => IncrementCount(t.Result),
TaskScheduler.FromCurrentSynchroniztionContext());
task.Start();
当你正在作用于不同的线程,你需要使用Dispatcher.BeginInvoke
上运行势必UI
集合的更新
我有这样的在下面的博客问题的解决方案..
http://bathinenivenkatesh.blogspot.co.uk/2011/07/wpf-build-more-responsive-ui.html
它提供了详细的说明和代码片段...