当进行winform的开发时,经常遇到用时比较久的操作,在传统的单线程程序中,用户必须等待这个耗时操作完成以后才能进行下一步的操作,这个时候,多线程编程就派上用场了,将这个耗时的操作放到一个新的子线程中,启动子线程完成操作,而不影响主线程的正常工作。
那么这个时候问题来了,当在子线程中需要操作界面上控件的参数时就不能简单的操作控件参数了,因为这会引起跨线程安全错误(子线程不是控件的初始化线程),具体原因不多讲,下面讲一下怎么解决子线程操作主线程控件的问题:
具体代码如下:
//0初始;1导入2暂停3恢复4终止
private void ButtonState(int state)
{
switch (state)
{
case :
btnImport.Enabled = true;
btnSuspend.Enabled = false;
btnResume.Enabled = false;
btnInterrupt.Enabled = false;
break;
case :
btnImport.Enabled = true;
btnSuspend.Enabled = true;
btnResume.Enabled = false;
btnInterrupt.Enabled = true;
break;
case :
btnImport.Enabled = true;
btnSuspend.Enabled = false;
btnResume.Enabled = true;
btnInterrupt.Enabled = true;
break;
case :
break;
case :
break;
}
}
//界面按钮事件
private void btnImport_ItemClick(object sender, ItemClickEventArgs e)
{
ButtonState();
ImportThread = new Thread(new ThreadStart(MyThread));
ImportThread.Start();
msIsAliveThreadName = "ImportThread";
}
//线程函数
private void MyThread()
{
//其他操作
FormState();
} public void FormState(int formState)
{
if (InvokeRequired)
{
System.EventArgs e = new MyEvents(formState);
object[] pList = { this, e };
//通过委托运行事件
BeginInvoke(new MyEventsHandler(UpdateUI_ButtonState), pList);
}
else
{
//非挂线程修改
}
} //事件委托
private delegate void MyEventsHandler(object sender, MyEvents e); //事件函数
private void UpdateUI_ButtonState(object sender, MyEvents e)
{
this.ButtonState(e.FormState);
}
//事件参数
public class MyEvents : EventArgs
{
public int FormState;
public MyEvents(int formState)
{
FormState = formState;
}
}