C#中在线程中访问主Form控件的问题

本文介绍如何在C#中解决线程与Form控件交互的问题,通过使用Invoke方法实现线程安全地更新UI元素,如ListBox的内容。提供了一个具体的示例程序,展示如何在后台线程中执行任务,并安全地将结果显示到界面。

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});
}

}

}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值