C#多线程与跨线程访问界面控件的方法


本文实例讲述了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()); 
}

2.使用委托
复制代码 代码如下:
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#程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3