C#多线程与跨线程访问界面控件的方法
程序员文章站
2023-12-13 10:46:10
本文实例讲述了c#多线程与跨线程访问界面控件的方法。分享给大家供大家参考。具体分析如下:
在编写winform访问webservice时,常会遇到因为网络延迟造成界面卡死...
本文实例讲述了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#程序设计有所帮助。