C#不允许直接从线程中访问Form里的控件,比如希望在线程里修改Form里的一个TextBox的内容等等,唯一的做法是使用Invoke方法,下面是一个MSDN里的Example,很说明问题:
usingSystem;
usingSystem.Drawing;
usingSystem.Windows.Forms;
usingSystem.Threading;
publicclassMyFormControl:Form
...{
publicdelegatevoidAddListItem(StringmyString);
publicAddListItemmyDelegate;
privateButtonmyButton;
privateThreadmyThread;
privateListBoxmyListBox;
publicMyFormControl()
...{
myButton=newButton();
myListBox=newListBox();
myButton.Location=newPoint(72,160);
myButton.Size=newSize(152,32);
myButton.TabIndex=1;
myButton.Text="Additemsinlistbox";
myButton.Click+=newEventHandler(Button_Click);
myListBox.Location=newPoint(48,32);
myListBox.Name="myListBox";
myListBox.Size=newSize(200,95);
myListBox.TabIndex=2;
ClientSize=newSize(292,273);
Controls.AddRange(newControl[]...{myListBox,myButton});
Text="'Control_Invoke'example";
myDelegate=newAddListItem(AddListItemMethod);
}
staticvoidMain()
...{
MyFormControlmyForm=newMyFormControl();
myForm.ShowDialog();
}
publicvoidAddListItemMethod(StringmyString)
...{
myListBox.Items.Add(myString);
}
privatevoidButton_Click(objectsender,EventArgse)
...{
myThread=newThread(newThreadStart(ThreadFunction));
myThread.Start();
}
privatevoidThreadFunction()
...{
MyThreadClassmyThreadClassObject=newMyThreadClass(this);
myThreadClassObject.Run();
}
}
publicclassMyThreadClass
...{
MyFormControlmyFormControl1;
publicMyThreadClass(MyFormControlmyForm)
...{
myFormControl1=myForm;
}
StringmyString;
publicvoidRun()
...{

for(inti=1;i<=5;i++)
...{
myString="Stepnumber"+i.ToString()+"executed";
Thread.Sleep(400);
//Executethespecifieddelegateonthethreadthatowns
//'myFormControl1'control'sunderlyingwindowhandlewith
//thespecifiedlistofarguments.
myFormControl1.Invoke(myFormControl1.myDelegate,
newObject[]...{myString});
}
}
}
本文介绍如何在C#中解决线程与Form控件交互的问题,通过使用Invoke方法实现线程安全地更新UI元素,如ListBox的内容。提供了一个具体的示例程序,展示如何在后台线程中执行任务,并安全地将结果显示到界面。
174

被折叠的 条评论
为什么被折叠?



