c# Chart 动态曲线更新

karl_city 2014-07-15 11:14:15
XY散点图,以数组为数据源,实时更新时要用时钟才能完成

private void button2_Click(object sender, EventArgs e)
{
timer1.Start();

}
int k;

ushort[] xx = new ushort[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ushort[] yy = new ushort[10] { 2, 3, 5, 7, 8, 9, 3, 6, 9, 0 };

private void timer1_Tick(object sender, EventArgs e)
{
Random num=new Random();

if (++k >= 10) k = 0;


chart1.ChartAreas[0].CursorX.Position = k;


chart1.Series[0].Points.RemoveAt(k);

yy[k] = (ushort)(num.Next( DateTime.Now.Second));

chart1.Series[0].Points.InsertXY(k, k,yy[k]);

// chart1.Series[0].Points.DataBindXY(xx, yy);

}

如上代码,100ms时钟,每次更新一个数据点,且游标能移动


如果不用时钟,采用for循环或者while循环, 加上线程休眠,出不了效果,代码如下:
private void button3_Click(object sender, EventArgs e)
{

Random num = new Random();

while (true)
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(100);

chart1.ChartAreas[0].CursorX.Position =i;


chart1.Series[0].Points.RemoveAt(i);

yy[i] = (ushort)(num.Next(DateTime.Now.Second));

chart1.Series[0].Points.InsertXY(i, i, yy[i]);
}
}

}

不知道是不是chart的更新要占用特别的的“时间片段”,所有线程休眠有冲突啊?
...全文
957 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
xian_wwq 2014-07-16
  • 打赏
  • 举报
回复
引用 楼主 karl_city 的回复:
XY散点图,以数组为数据源,实时更新时要用时钟才能完成 private void button2_Click(object sender, EventArgs e) { timer1.Start(); } int k; ushort[] xx = new ushort[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; ushort[] yy = new ushort[10] { 2, 3, 5, 7, 8, 9, 3, 6, 9, 0 }; private void timer1_Tick(object sender, EventArgs e) { Random num=new Random(); if (++k >= 10) k = 0; chart1.ChartAreas[0].CursorX.Position = k; chart1.Series[0].Points.RemoveAt(k); yy[k] = (ushort)(num.Next( DateTime.Now.Second)); chart1.Series[0].Points.InsertXY(k, k,yy[k]); // chart1.Series[0].Points.DataBindXY(xx, yy); } 如上代码,100ms时钟,每次更新一个数据点,且游标能移动 如果不用时钟,采用for循环或者while循环, 加上线程休眠,出不了效果,代码如下: private void button3_Click(object sender, EventArgs e) { Random num = new Random(); while (true) { for (int i = 0; i < 10; i++) { Thread.Sleep(100); chart1.ChartAreas[0].CursorX.Position =i; chart1.Series[0].Points.RemoveAt(i); yy[i] = (ushort)(num.Next(DateTime.Now.Second)); chart1.Series[0].Points.InsertXY(i, i, yy[i]); } } } 不知道是不是chart的更新要占用特别的的“时间片段”,所有线程休眠有冲突啊?
chart要更新肯定需要时间,但问题出在Thread.Sleep(100)上; 建议将sleep时间缩短

          DateTime currentTime = DateTime.Now;

            while (true)
            {
                System.Threading.Thread.Sleep(1);
                DateTime lastTime = DateTime.Now;
                TimeSpan ts1 = lastTime - currentTime;
                if (ts1.Milliseconds >= 100)
                {
                    currentTime = lastTime;
                    //这块是逻辑处理代码
                    DoingSth();
                }
            }

放在主线程中,肯定会出现界面卡顿的现象。 建议将数据更新放在thread中,因为涉及UI处理,肯定要用委托。

110,566

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧