版权声明:authored by zzubqh https://blog.csdn.net/qq_36810544/article/details/84644016
最近做算法的移植和demo展示,算是把大学里的C++ C#又给复习了一遍。C#的窗体程序中,在子线程中访问主线程的控件,直接访问会引发异常,提示不在同一个进程里之类的错误。所以,在timer控件的定时事件或者在新线程里控制进度条这种任务都会涉及到子线程访问主线程里的控件问题。解决方案很简单,声明委托,然后在委托中判断是否在主线程中,不是就利用控件的Invoke方法。
大致流程:
- 声明委托
delegate void ShowProgressDelegate(int totalStep, int currentStep);
- 委托实现
private void ShowProgress(int totalStep, int currentStep)
{
if(progressBar1.InvokeRequired == false)
{
progressBar1.Maximum = totalStep;
progressBar1.Value = currentStep;
}
else
{
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
progressBar1.Invoke(showProgress, new object[] { totalStep, currentStep });
}
}
- 在需要的地方调用
private void Do()
{
progress_thread = new System.Threading.Thread(new System.Threading.ThreadStart(TheadProcess));
progress_thread.Start();
}
private void TheadProcess()
{
int seconds = (int)analyer_timer.Interval * 2;
for (int i = 0; i<seconds; i+=seconds/200)
{
System.Threading.Thread.Sleep(100);
ShowProgress(seconds, i+1);
}
}
把这个移植完就可以继续玩我的python了,python用习惯了,写c居然会忘";",而且#include怎么看都是注释,重度python患者啊!