我有一个C#图表控件,我像这样绑定数据。
chart.Series[0].Points.DataBindXY(xAxis, yAxis);
where xAxis is List<String> and yAxis is List<Double>
在另一个线程上,xAxis和yAxis不断更新(多次调用.Add())
但是,除非我再次调用DataBindXY(),否则图表不会更新。然而,这似乎会导致问题,因为每隔一段时间我都会收到
Error: "Collection was modified; enumeration operation may not execute."
这会导致我的程序在某些时候崩溃
Error: "system.reflection.targetinvocationexception' occurred in mscorlib.dll"
-Is我在更新的时候还缺少什么吗?或者,如果您需要更多信息,请让我知道。
发布于 2011-09-12 15:53:54
您需要在更新方法和 DataBindXY方法中添加锁定或同步。不能同时修改列表和读取列表,因为列表上的操作不是线程安全的。
我推荐阅读这篇关于C#中的线程同步的介绍(或许多其他介绍中的一个):http://msdn.microsoft.com/en-us/library/ms173179.aspx
编辑:这是一个如何做到这一点的例子:
Object lockOnMe = new Object();
... in your Add loop
(int i = 0; i < dacPoints.Count; i += 1) {
TimeSpan span = new TimeSpan(0, 0, i + 1);
lock (lockOnMe) {
presenter.addPoint(span.ToString(), dacPoints[i]);
}
System.Threading.Thread.Sleep(200);
}
... when calling DataBindXY()
lock (lockOnMe) {
// Note that I copy the lists here.
// This is because calling DataBindXY is not necessarily a serial,
// blocking operation, and you don't want the UI thread touching
// these lists later on after we exit the lock
chart.Series[0].Points.DataBindXY(xAxis.ToList(), yAxis.ToList());
}
发布于 2011-09-12 15:59:26
图表控件读取数据源一次(当您发出DataBindXY调用时),这就是当您修改集合时它不会更新的原因。
偶尔出现问题的原因是,当图表从集合中读取时,执行更新的后台线程正在更改集合。
最好将图表轴作为在UI线程上创建的ObservableCollection。然后,您可以响应CollectionChanged事件,指示图表执行DataBindXY。
但是,为了正确使用它,您的后台线程需要调用对UI线程上的集合的添加调用。如果您有对图表控件的引用,则可以使用control.BeginInvoke调用。
https://stackoverflow.com/questions/7390544
复制