Csharp/C#教程:在多线程中调用winform窗体控件的实现方法分享

本文实例讲述了在C#中实现多线程中调用winform窗体控件的方法,对于C#程序设计的学习有着很好的借鉴参考价值。具体方法如下:

首先,由于Windows窗体控件本质上不是线程安全的。因此如果有两个或多个线程适度操作某一控件的状态(setvalue),则可能会迫使该控件进入一种不一致的状态。还可能出现其他与线程相关的bug,包括争用和死锁的情况。于是在调试器中运行应用程序时,如果创建某控件的线程之外的其他线程试图调用该控件,则调试器会引发一个InvalidOperationException

本文用一个很简单的示例来讲解这个问题(在窗体上放一个TextBox和一个Button,点击Button后,在新建的线程中设置TextBox的值)

解决办法一:关闭该异常检测的方式来避免异常的出现

经过测试发现此种方法虽然避免了异常的抛出,但是并不能保证程序运行结果的正确性(比如多个线程同时设置TextBox1的Text时,很难预计最终TextBox1的Text是什么)

usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Threading; namespacewinformTest { publicpartialclassForm1:Form { publicForm1() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls=false;//这一行是关键 } privatevoidbutton1_Click(objectsender,EventArgse) { SetTextBoxValue(); } voidSetTextBoxValue() { TextBoxSetValuetbsv=newTextBoxSetValue(this.textBox1,"Method1"); ThreadStartTS=newThreadStart(tbsv.SetText); ThreadT=newThread(TS); T.Start(); } classTextBoxSetValue { privateTextBox_TextBox; privatestring_Value; publicTextBoxSetValue(TextBoxTxtBox,StringValue) { _TextBox=TxtBox; _Value=Value; } publicvoidSetText() { _TextBox.Text=_Value; } } } }

解决办法二:通过委托安全调用

usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; namespacewinformTest { publicpartialclassForm2:Form { publicForm2() { InitializeComponent(); } privatevoidbutton1_Click(objectsender,EventArgse) { SetTextBoxValue(); } privatedelegatevoidCallSetTextValue(); //通过委托调用 voidSetTextBoxValue() { TextBoxSetValuetbsv=newTextBoxSetValue(this.textBox1,"Method2"); if(tbsv.TextBox.InvokeRequired) { CallSetTextValuecall=newCallSetTextValue(tbsv.SetText); tbsv.TextBox.Invoke(call); } else { tbsv.SetText(); } } classTextBoxSetValue { privateTextBox_TextBox; privatestring_Value; publicTextBoxSetValue(TextBoxTxtBox,StringValue) { _TextBox=TxtBox; _Value=Value; } publicvoidSetText() { _TextBox.Text=_Value; } publicTextBoxTextBox{ set{_TextBox=value;} get{return_TextBox;} } } } }

第三解决办法:利用BackgroundWorker控件

usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Threading; namespacewinformTest { publicpartialclassForm3:Form { publicForm3() { InitializeComponent(); } privatevoidbutton1_Click(objectsender,EventArgse) { using(BackgroundWorkerbw=newBackgroundWorker()) { bw.RunWorkerCompleted+=SetTextBoxValue; bw.RunWorkerAsync(); } } voidSetTextBoxValue(objectsender,RunWorkerCompletedEventArgse) { TextBoxSetValuetbsv=newTextBoxSetValue(this.textBox1,"Method3"); tbsv.SetText(); } classTextBoxSetValue { privateTextBox_TextBox; privatestring_Value; publicTextBoxSetValue(TextBoxTxtBox,StringValue) { _TextBox=TxtBox; _Value=Value; } publicvoidSetText() { _TextBox.Text=_Value; } } } }

用户不喜欢反应慢的程序。在执行耗时较长的操作时,使用多线程是明智之举,它可以提高程序UI的响应速度,使得一切运行显得更为快速。在Windows中进行多线程编程曾经是C++开发人员的专属特权,但是现在,可以使用所有兼容Microsoft.NET的语言来编写。

不过Windows窗体体系结构对线程使用制定了严格的规则。如果只是编写单线程应用程序,则没必要知道这些规则,这是因为单线程的代码不可能违反这些规则。然而,一旦采用多线程,就需要理解Windows窗体中最重要的一条线程规则:除了极少数的例外情况,否则都不要在它的创建线程以外的线程中使用控件的任何成员。本规则的例外情况有文档说明,但这样的情况非常少。这适用于其类派生自System.Windows.Forms.Control的任何对象,其中几乎包括UI中的所有元素。所有的UI元素(包括表单本身)都是从Control类派生的对象。此外,这条规则的结果是一个被包含的控件(如,包含在一个表单中的按钮)必须与包含它控件位处于同一个线程中。也就是说,一个窗口中的所有控件属于同一个UI线程。实际中,大部分Windows窗体应用程序最终都只有一个线程,所有UI活动都发生在这个线程上。这个线程通常称为UI线程。这意味着您不能调用用户界面中任意控件上的任何方法,除非在该方法的文档说明中指出可以调用。该规则的例外情况(总有文档记录)非常少而且它们之间关系也不大。请注意,以下代码是非法的:

privateThreadmyThread; privatevoidForm1_Load(objectsender,EventArgse) { myThread=newThread(newThreadStart(RunsOnWorkerThread)); myThread.Start(); } privatevoidRunsOnWorkerThread() { label1.Text="myThread线程调用UI控件"; }

如果您在.NETFramework1.0版本中尝试运行这段代码,也许会侥幸运行成功,或者初看起来是如此。这就是多线程错误中的主要问题,即它们并不会立即显现出来。甚至当出现了一些错误时,在第一次演示程序之前一切看起来也都很正常。但不要搞错—我刚才显示的这段代码明显违反了规则,并且可以预见,任何抱希望于“试运行时良好,应该就没有问题”的人在即将到来的调试期是会付出沉重代价的。

下面我们来看看有哪些方法可以解决这一问题。

一、System.Windows.Forms.MethodInvoker类型是一个系统定义的委托,用于调用不带参数的方法。

privateThreadmyThread; privatevoidForm1_Load(objectsender,EventArgse) { myThread=newThread(newThreadStart(RunsOnWorkerThread)); myThread.Start(); } privatevoidRunsOnWorkerThread() { MethodInvokermi=newMethodInvoker(SetControlsProp); BeginInvoke(mi); } privatevoidSetControlsProp() { label1.Text="myThread线程调用UI控件"; }

二、直接用System.EventHandle(可带参数)

privateThreadmyThread; privatevoidForm1_Load(objectsender,EventArgse) { myThread=newThread(newThreadStart(RunsOnWorkerThread)); myThread.Start(); } privatevoidRunsOnWorkerThread() { //DoSomethingSlow(); stringpList="myThread线程调用UI控件"; label1.BeginInvoke(newSystem.EventHandler(UpdateUI),pList); } //直接用System.EventHandler,没有必要自定义委托 privatevoidUpdateUI(objecto,System.EventArgse) { //UI线程设置label1属性 label1.Text=o.ToString()+"成功!"; }

三、包装Control.Invoke

虽然第二个方法中的代码解决了这个问题,但它相当繁琐。如果辅助线程希望在结束时提供更多的反馈信息,而不是简单地给出“Finished!”消息,则BeginInvoke过于复杂的使用方法会令人生畏。为了传达其他消息,例如“正在处理”、“一切顺利”等等,需要设法向UpdateUI函数传递一个参数。可能还需要添加一个进度栏以提高反馈能力。这么多次调用BeginInvoke可能导致辅助线程受该代码支配。这样不仅会造成不便,而且考虑到辅助线程与UI的协调性,这样设计也不好。对这些进行分析之后,我们认为包装函数可以解决这两个问题。

privateThreadmyThread; privatevoidForm1_Load(objectsender,EventArgse) { myThread=newThread(newThreadStart(RunsOnWorkerThread)); myThread.Start(); } privatevoidRunsOnWorkerThread() { ////DoSomethingSlow(); for(inti=0;i<100;i++) { ShowProgress(Convert.ToString(i)+"%",i); Thread.Sleep(100); } } publicvoidShowProgress(stringmsg,intpercentDone) { //WraptheparametersinsomeEventArgs-derivedcustomclass: System.EventArgse=newMyProgressEvents(msg,percentDone); object[]pList={this,e}; BeginInvoke(newMyProgressEventsHandler(UpdateUI),pList); } privatedelegatevoidMyProgressEventsHandler(objectsender,MyProgressEventse); privatevoidUpdateUI(objectsender,MyProgressEventse) { lblStatus.Text=e.Msg; myProgressControl.Value=e.PercentDone; } publicclassMyProgressEvents:EventArgs { publicstringMsg; publicintPercentDone; publicMyProgressEvents(stringmsg,intper) { Msg=msg; PercentDone=per; } }

ShowProgress方法对将调用引向正确线程的工作进行封装。这意味着辅助线程代码不再担心需要过多关注UI细节,而只要定期调用ShowProgress即可。

如果我提供一个设计为可从任何线程调用的公共方法,则完全有可能某人会从UI线程调用这个方法。在这种情况下,没必要调用BeginInvoke,因为我已经处于正确的线程中。调用Invoke完全是浪费时间和资源,不如直接调用适当的方法。为了避免这种情况,Control类将公开一个称为InvokeRequired的属性。这是“只限UI线程”规则的另一个例外。它可从任何线程读取,如果调用线程是UI线程,则返回假,其他线程则返回真。这意味着我可以按以下方式修改包装:

publicvoidShowProgress(stringmsg,intpercentDone) { if(InvokeRequired) { //Asbefore //... } else { //We'realreadyontheUIthreadjust //callstraightthrough. UpdateUI(this,newMyProgressEvents(msg,PercentDone)); } }

线程打开窗体的问题:

usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; namespaceWindowsApplication36 { publicpartialclassForm1:Form { publicForm1() { InitializeComponent(); } privatevoidForm1_Load(objectsender,EventArgse) { } privatevoidbutton1_Click(objectsender,EventArgse) { newSystem.Threading.Thread(newSystem.Threading.ThreadStart(invokeShow)).Start(); } publicvoidinvokeShow() { Formf1=newForm(); this.Invoke(newSystem.EventHandler(this.showForm),newobject[]{f1,null}); } publicvoidshowForm(objectsender,EventArgse) { Formf1=senderasForm; f1.ShowDialog(); } } } 您可能感兴趣的文章:C#调用Java代码的方法介绍C#调用Java类的实现方法C#/Java连接sqlite与使用技巧C#调用JavaWebservice服务遇到的问题汇总C#通过html调用WinForm的方法Winform实现调用asp.net数据接口实例winform调用javascript的小例子WinForm窗体调用WCF服务窗体卡死问题C#Winform调用系统接口操作INI配置文件的代码WinForm调用jar包的方法分析

标签: 线程 fo form 多线程 winform info orm 窗体 win 方法 调用 rm for nf infor

简单上述就是C#学习教程:在多线程中调用winform窗体控件的实现方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/905695.html

(0)
上一篇 2021年10月23日
下一篇 2021年10月23日

精彩推荐