C#多线程与跨线程访问界面控件的方法
更新时间:2015年03月03日 11:19:58 作者:寻i
这篇文章主要介绍了C#多线程与跨线程访问界面控件的方法,实例分析了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();
}
{
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());
}
/// 应用程序的主入口点。
/// </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);
}
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#程序设计有所帮助。
相关文章
.net 通过 WebAPI 调用nsfwjs 进行视频鉴别功能
这篇文章主要介绍了.net 通过 WebAPI 调用 nsfwjs 进行视频鉴别,文末给大家提到了FFMPEG获取视频关键帧并保存成jpg图像的相关知识,需要的朋友可以参考下2021-09-09
C#实现的Windows剪贴板监视器功能实例【附demo源码下载】
这篇文章主要介绍了C#实现的Windows剪贴板监视器功能,结合实例形式分析了C#实现剪贴板监视功能所涉及的相关Windows API函数与使用技巧,需要的朋友可以参考下2016-08-08


最新评论