0
点赞
收藏
分享

微信扫一扫

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);
}



举报

相关推荐

0 条评论