1 在代码中开启一个子线程
Thread cabService = new Thread(new ThreadStart(<strong>dataReceiver</strong>));
cabService.Start();
每隔2s ,产生一个数据
public void dataReceiver()
{
while(true)
{
x = new Random((int)(System.DateTime.Now.Second)).Next(3, 50);
Console.WriteLine("产生数据!"+x);
if(monitor!=null)
{
<strong>monitor</strong>(x);
}
Thread.Sleep(2000);
}
}
2 定义代理和事件
public delegate void <strong>DataMonitor</strong>(int data);
public event <strong>DataMonitor</strong> monitor ;
3 在monitor 上面添加处理
monitor += new DataMonitor(cab.<strong>UpdateChart</strong>);
cab.updateChart 就是需要更新界面图标数据的代码
4 在Cab类当中顶一个这样一个函数,实现界面更新
public void UpdateChart(int x)
{
Action a = new Action(<strong>updateSerial</strong>);
data = x;
cab_chart.Dispatcher.BeginInvoke(a);
}
public void <strong>updateSerial</strong>()
{
for (int i = _pointCount - 1; i > 0;i-- )
{
dataSeries.DataPoints[i-1] = dataSeries.DataPoints[i];
}
DataPoint datapoint = new DataPoint();
datapoint.AxisXLabel = (_pointCount - 1) + "";
datapoint.YValue = data;
dataSeries.DataPoints.Add(datapoint);
cab_chart.Series.Clear();
cab_chart.Series.Add(dataSeries);
}
5 这和android的线程模型极为相似,子线程的数据都需要一个Handler 来执行界面更新 ,ok!