[英]C# Adding points to Chart in realtime
我有一個關於為圖表添加點的問題。
我的Windows窗體應用程序正在使用一個線程從另一台服務器獲取Y值。 每500毫秒我得到一個新的值(字符串)應該作為一個點添加,但我不知道如何做到這一點。 如果點將實時顯示並且不僅在結束過程之后,那將是非常好的。 我認為這不是一個真正困難的問題,但我沒有找到解決方案。
線:
private void Work()
{
int counter = 0;
while (true)
{
counter++;
WebClient code = new WebClient();
speed_str = code.DownloadString("http://192.168.19.41/speedfile.html");
speedval = Convert.ToDouble(speed_str);
Console.WriteLine(speedval.ToString() + "\n Times executed: " + counter);
Thread.Sleep(1000);
}
}
配置和圖表
Thread thread = new Thread(new ThreadStart(this.Work));
thread.IsBackground = true;
thread.Name = "My Worker.";
thread.Start();
//Speed
Series speed = new Series("Speed[m/s]");
speed.ChartType = SeriesChartType.Spline;
//Engines Left
engleft = new Series("Engines Left");
engleft.ChartType = SeriesChartType.Spline;
Engines.Series.Add(engleft);
engleft.Points.Clear();
string speed_read = Console.ReadLine();
感謝幫助 :)
您手上有經典的Producer-Consumer
場景。
這意味着一個線程產生一個項目(后台線程)
而另一個消耗它(UI線程)。
生產者和消費者之間進行通信的一種方式是使用以下事件:
class Producer
{
public event EventHandler<double> YSeriesEvent;
private Thread thread;
public Producer()
{
thread = new Thread(new ThreadStart(this.Work));
thread.IsBackground = true;
thread.Name = "My Worker.";
}
public void Start()
{
thread.Start();
}
private void Work()
{
int counter = 0;
while (true)
{
counter++;
WebClient code = new WebClient();
speed_str = code.DownloadString("http://192.168.19.41/speedfile.html");
speedval = Convert.ToDouble(speed_str);
YSeriesEvent?.Invoke(this, speedval);
}
}
}
然后,在您的表單中,您可能會這樣:
class MyForm : Form
{
private Producer producer;
public MyForm()
{
producer = new Producer();
producer.YSeriesEvent += MyHandler ;
Load+= (sender, args) => producer.Start();
}
private void MyHandler(object o, double val)
{
Invoke(new Action(() =>
{
//add value to chart here
}));
}
}
請注意,WinForms是單線程的,這意味着沒有線程可以直接在UI元素上工作,除非它是UI線程。
這就是我調用Invoke
方法的原因 - 它只是卸載了要在UI線程上執行的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.