C#多线程与跨线程访问界面控件的方法
本文实例讲述了C#多线程与跨线程访问界面控件的方法。分享给大家供大家参考。具体分析如下:
在编写WinForm访问WebService时,常会遇到因为网络延迟造成界面卡死的现象。启用新线程去访问WebService是一个可行的方法。
典型的,有下面的启动新线程示例:
privatevoidLoadRemoteAppVersion() { if(FileName.Text.Trim()=="")return; StatusLabel.Text="正在加载"; S_Controllers_Bins.S_Controllers_BinsSoapClientservice=newS_Controllers_Bins.S_Controllers_BinsSoapClient(); S_Controllers_Bins.Controllers_Binsm=service.QueryFileName(FileName.Text.Trim()); if(m!=null) { //todo: StatusLabel.Text="加载成功"; }else StatusLabel.Text="加载失败"; } privatevoidBtnLoadBinInformation(objectsender,EventArgse) { ThreadnonParameterThread=newThread(newThreadStart(LoadRemoteAppVersion)); nonParameterThread.Start(); }
运行程序的时候,如果要在线程里操作界面控件,可能会提示不能跨线程访问界面控件,有两种处理方法:
1.启动程序改一下:
///<summary> ///应用程序的主入口点。 ///</summary> [STAThread] staticvoidMain() { Application.EnableVisualStyles(); System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls=false; Application.SetCompatibleTextRenderingDefault(false); Application.Run(newForm1()); }
2.使用委托
publicdelegatevoidLoadRemoteAppVersionDelegate();//定义委托变量 privatevoidBtnLoadBinInformation(objectsender,EventArgse) { LoadRemoteAppVersionDelegatefunc=newLoadRemoteAppVersionDelegate(LoadRemoteAppVersion);//<spanstyle="font-family:Arial,Helvetica,sans-serif;">LoadRemoteAppVersion不用修改</span> func.BeginInvoke(null,null); }
希望本文所述对大家的C#程序设计有所帮助。