本文实例讲述了C#多线程与跨线程访问界面控件的方法。分享给大家供大家参考。具体分析如下:
在编写WinForm访问WebService时,常会遇到因为网络延迟造成界面卡死的现象。启用新线程去访问WebService是一个可行的方法。
典型的,有下面的启动新线程示例:
private void LoadRemoteAppVersion() { if (FileName.Text.Trim() == "") return; StatusLabel.Text = "正在加载"; S_Controllers_Bins.S_Controllers_BinsSoapClient service = new S_Controllers_Bins.S_Controllers_BinsSoapClient(); S_Controllers_Bins.Controllers_Bins m = service.QueryFileName(FileName.Text.Trim()); if (m != null) { //todo: StatusLabel.Text = "加载成功"; }else StatusLabel.Text = "加载失败"; } private void BtnLoadBinInformation(object sender, EventArgs e) { Thread nonParameterThread = new Thread(new ThreadStart(LoadRemoteAppVersion)); nonParameterThread.Start(); }
运行程序的时候,如果要在线程里操作界面控件,可能会提示不能跨线程访问界面控件,有两种处理方法:
1.启动程序改一下:
/// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
public delegate void LoadRemoteAppVersionDelegate(); //定义委托变量 private void BtnLoadBinInformation(object sender, EventArgs e) { LoadRemoteAppVersionDelegate func = new LoadRemoteAppVersionDelegate(LoadRemoteAppVersion);//<span style="font-family: Arial, Helvetica, sans-serif;">LoadRemoteAppVersion不用修改</span> func.BeginInvoke(null, null); }
希望本文所述对大家的C#程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。