本文實例講述了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#程序設計有所幫助。