我有一个窗体,其中有1个按钮(为简单起见)。需要帮助在Windows窗体应用程序中使用C#.net 4.0实时图表的问题
在点击这个按钮,我使用ParameterizedThreadStart在一个单独的后台线程启动的算法。
现在,这个算法在需要被显示在图表中固定的时间间隔产生输出。
如果我在初始化MainForm的图表,并通过此对象的算法线程,那么它不容许,并表示图表的分配和访问是跨线程。
如果我有ALGO类的内部图表对象,那么它不显示图表蜱。只显示一个空白表格(通过执行_chart.Show())并且不显示任何刻度。
此外,如何AddPoint到图表,我用chart.Invoke(chart.AddPointDelegate,则params)在第二种情况,但卡在调用。
请帮我一条出路。
编辑:
public MyForm()
{
InitializeComponent();
_getChartDataDelegate = AddTickToChart;
}
public AddTickChartDelegate _getChartDataDelegate;
public void AddTickToChart(ChartTickPoint point)
{
DateTime x = point.X;
double y = point.Y;
object[] parameters = { x, y };
if (this.InvokeRequired)
{// this prevents the invoke loop
this.Invoke(new Action<ChartTickPoint>(_chart.chartDelegate), new object[] { point }); // invoke call for _THIS_ function to execute on the UI thread
}
else
{
//function logic to actually add the datapoint goes here
//_chart.Invoke(_chart.chartDelegate, parameters);
_chart.AddTick(point);
}
}
private void button_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ParameterizedThreadStart(MyUtils.RunAlgo));
AlgoData algoData = new AlgoData(myFile, _getChartDataDelegate);
thread.Start(algoData);
}
// MyForm ends
// Intermediate static Util class to run algo
MyUtils.RunAlgo(object obj)
{
// new Algo
// Get delegate from algoData obj
algo.Run(delegateInTheMyForm);
}
// Algo class's Run
Run(AddTickChartDelegate delegateInTheMyForm)
{
delegateInTheMyForm(point);
}
// Chart class
public AddTickChartDelegate chartDelegate;
public void AddTick(ChartTickPoint point)
{
DateTime timeStamp = point.X;
double y = point.Y;
foreach (Series ptSeries in chart1.Series)
{
AddNewPoint(timeStamp, y, ptSeries);
}
}
这里我再次在MyForm的类越来越善于this.Invoke(新动作..)跨线程问题。
此外,
If i replace this.Invoke(Action..) with chart.Invoke(..)
if (this.InvokeRequired)
{
_chart.Invoke(_chart.chartDelegate, point);
// instead of Action...
}
然后它通过,但图表形式不响应并且是空的。
所以我需要有工作线程(算法中类)内部窗体类的处理?第一块这个.Invoke(..)部分是什么意思? – 2011-04-13 16:49:31
见编辑后 – DarkSquirrel42 2011-04-13 17:15:49
为什么我们需要2个引用(表单和委托)?所以我只会将代表的参考传递给算法类。这个委托在Form类中定义,对吧?第一个this.invoke(new Action ..)在做什么? – 2011-04-13 17:31:36