如何动态更新Windows窗体图表中的数据?

时间:2016-11-30 01:15:28

标签: c# multithreading winforms charts

在这里公平警告,我是C#和Windows表单的新手,所以我可能会以错误的方式接近它。我有一个应用程序正在计算需要添加到我的Windows窗体图表系列中的实时数据点。该数据每10毫秒频繁计算,并且需要接近该速率更新,优选地在+50毫秒内。

Forms应用程序和图表是使用visual studio中包含的图形构建器构建的,因此生成的源文件具有自动生成的警告,不会修改它们:do not modify the contents of this method with the code editor.

我所做的是使用属性修饰符将图表设为Public,以便我可以在我的代码中访问它。在我的主程序中,我试图做这样的事情:

static Form1 form;
Series series = new Series();
static void Main() {

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                form = new Form1();
                new UpdateLoop.Start();
                Application.Run(form);  

}
void Start() {
            series.ChartArea = "ChartArea1";
            series.ChartType = SeriesChartType.Line;
            series.Legend = "Legend1";
            series.Name = "Test series";
            series.Points.Add(new DataPoint(0D, 0D)); //add start point
}

 void tElapse(object sender, ElapsedEventArgs e) { //this is called every 10 miliseconds


            double points[] = ...; //get points from elsewhere

                for(int i = 0 ; i < points.Count; i+=2) {
                    series.Points.Add(new DataPoint(points[i], points[i+1]));

                }
            }
  }

当我运行这个时会发生的事情是它添加了起点就好了,创建了图表,但是,它只能在它给我System.InvalidOperationException之前添加大约1-2个点并警告我我#39;在控制图1(我的图表)上进行跨线程操作。显然,我不应该以这种方式从不同的线程添加数据。但是,我需要一种方法来做到这一点。我怎么能够?

ps:我知道Java已经同步(我不知道如何使用)进行跨线程操作,C#有类似的东西吗?

编辑:忘了提一下:我必须在两个线程上有这个,我也不希望图形线程运行主程序。另外,我相当肯定这是不好的做法。

0 个答案:

没有答案