我有一個窗體,其中有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