C#表单 - 更新图表

时间:2018-01-08 04:16:10

标签: c# multithreading charts invoke

我收到错误消息:“收集已修改;枚举操作可能无法执行。” 我能够通过以下代码隔离并重现错误:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        Thread tester;
        int testNum = 0;

        public Form1()
        {
            InitializeComponent();

            tester = new Thread(threadTester);
            tester.IsBackground = true;
            tester.Start();

        }

        public void threadTester()
        {
            bool testWhile = true;

            while (testWhile)
            {
                Thread.Sleep(1);

                testNum++;

                updateChart();

            }
        }

        public void updateChart()
        {
            testChart.Series["Series1"].Points.AddXY(testNum, testNum);
        }
    }
}

在阅读其他一些类似的问题之后,我猜我收到了这个错误,因为该程序试图显示/更新图表,同时向图表集合添加数据点。

我读过这个,因为我是从一个单独的线程添加点,我应该使用Invoke方法,但我无法弄清楚如何在我的代码中正确实现它。

我希望有人可以帮我解决这个问题。

0 个答案:

没有答案