private void Form1_Load(object sender, EventArgs e)
{
Thread newthread = new Thread(new ThreadStart(BackgroundProcess));
newthread.Start(); } /// <summary>
/// 定义一个代理
/// </summary>
private delegate void CrossThreadOperationControl(); private void BackgroundProcess()
{
// 将代理实例化为一个匿名代理
CrossThreadOperationControl CrossDelete = delegate()
{
int i = ;
while (i < )
{
// 向列表框增加一个项目
listBox1.Items.Add("Item " + i.ToString());
i++;
}
label1.Text = "我在新线程里访问这个lable!";
listBox1.Items.Add(label1.Text);
};
listBox1.Invoke(CrossDelete);
}

收集一下,在C# winform编程中多线程操作控件时,可以有下面种方法:

1. 又看到一种方法(2014.1.6):

1. 刚看到一种方法(2014.1.5):

 private void btnTest_Click(object sender, EventArgs e)
{
if (this.txtIP.Text.Trim() != "" && this.txtPort.Text.Trim() != "")
{
string proxy = this.txtIP.Text.Trim() + ":" + this.txtPort.Text.Trim();
string result = string.Empty;
this.btnTest.Enabled = false;
new Thread(delegate
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
HttpClient httpClient = new HttpClient();
httpClient.Proxy = new WebProxy(proxy);
httpClient.TimeOut = ;
object result;
try
{
string a = httpClient.Get("http://www.baidu.com", "", "", "", "", "get");
if (a != "")
{
result = "响应成功!";
}
else
{
result = "响应失败!";
}
}
catch
{
}
stopwatch.Stop();
result = result;
result = string.Concat(new object[]
{
result,
",响应花费:",
stopwatch.ElapsedMilliseconds,
"ms"
});
this.BeginInvoke(delegate
{
this.lbResult.Text = result;
this.btnTest.Enabled = true;
});
})
{
IsBackground = true
}.Start();
}
else
{
this.lbResult.Text = "请输入完整再提交!";
}
}

1. 直接使用表达式和Action()

 private void btnInitEnv_Click(object sender, EventArgs e)
{
//初始化环境时回显出来的文字不让看
try
{
this.textBoxOutPut.Clear();
this.btnInitEnv.Enabled = false;
this.labelStateInfo.Text = "";
this.labelStateInfo.ForeColor = Color.Red; if (!WriteToSerialPort("diags"))
{
this.btnInitEnv.Enabled = true;
return;
} Thread thread = new Thread(new ThreadStart(() =>
{
int i = ;
bool flagFind = false;
StringBuilder sb = new StringBuilder(); while (true)
{
Thread.Sleep();
this.Invoke(new Action(() =>
{
sb.Append(this.textBoxOutPut.Text);
this.textBoxOutPut.Clear();
if (sb.ToString().Contains("Entering recovery mode, starting command prompt"))
{
this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
DateTime.Now.ToString(PubilcConstVar.TimeFormat),
"Entering recovery mode, starting command prompt, Stop.\r\n"));
this.labelStateInfo.ForeColor = Color.Red;
this.labelStateInfo.Text = "初始化失败,请手动输入命令初始化";
flagFind = true;
this.btnInitEnv.Enabled = true;
}
else if (sb.ToString().Contains(":-)"))
{
this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
DateTime.Now.ToString(PubilcConstVar.TimeFormat),
"进入操作模式成功\r\n"));
this.labelStateInfo.ForeColor = Color.Blue;
this.labelStateInfo.Text = "初始化成功";
flagFind = true; //将业务按钮使能
EnableBussinessButtons();
}
})); if (flagFind || ++i > ) //找开标志或10秒超时中断
{
break;
}
} if (!flagFind)
{
this.Invoke(new Action(() =>
{
this.textBoxOutPut.Clear();
this.labelStateInfo.ForeColor = Color.Red;
this.labelStateInfo.Text = "初始化失败,超时";
this.btnInitEnv.Enabled = true; DisableBussinessButtons();
}));
}
})); thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
this.log.Write(ex.ToString());
}
}

2. 使用线程函数加action()

 private void btnInitEnv_Click(object sender, EventArgs e)
{
//初始化环境时回显出来的文字不让看
try
{
this.textBoxOutPut.Clear();
this.btnInitEnv.Enabled = false;
this.labelStateInfo.Text = "";
this.labelStateInfo.ForeColor = Color.Red; if (!WriteToSerialPort("diags"))
{
this.btnInitEnv.Enabled = true;
return;
} Thread thread = new Thread(new ThreadStart(MonitorOutPutThread)); thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
this.log.Write(ex.ToString());
}
}

线程函数:

 private void MonitorOutPutThread()
{
int i = ;
bool flagFind = false;
StringBuilder sb = new StringBuilder(); while (true)
{
Thread.Sleep();
this.Invoke(new Action(() =>
{
sb.Append(this.textBoxOutPut.Text);
this.textBoxOutPut.Clear();
if (sb.ToString().Contains("Entering recovery mode, starting command prompt"))
{
this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
DateTime.Now.ToString(PubilcConstVar.TimeFormat),
"Entering recovery mode, starting command prompt, Stop.\r\n"));
this.labelStateInfo.ForeColor = Color.Red;
this.labelStateInfo.Text = "初始化失败,请手动输入命令初始化";
flagFind = true;
this.btnInitEnv.Enabled = true;
}
else if (sb.ToString().Contains(":-)"))
{
this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,
DateTime.Now.ToString(PubilcConstVar.TimeFormat),
"进入操作模式成功\r\n"));
this.labelStateInfo.ForeColor = Color.Blue;
this.labelStateInfo.Text = "初始化成功";
flagFind = true; //将业务按钮使能
EnableBussinessButtons();
}
})); if (flagFind || ++i > ) //找开标志或10秒超时中断
{
break;
}
} if (!flagFind)
{
this.Invoke(new Action(() =>
{
this.textBoxOutPut.Clear();
this.labelStateInfo.ForeColor = Color.Red;
this.labelStateInfo.Text = "初始化失败,超时";
this.btnInitEnv.Enabled = true; DisableBussinessButtons();
}));
}
}

3. 就是使用委托,这个网上例子很多,不再实现

C# winform编程中多线程操作控件方法的更多相关文章

  1. 关于WinForm引用WPF窗体---在Winform窗体中使用WPF控件

    项目中有个界面展示用WPF实现起来比较简单,并且能提供更酷炫的效果,但是在WinForm中使用WPF窗体出现了问题,在网上找了一下有些人说Winform不能引用WPF的窗体,我就很纳闷,Win32都能 ...

  2. 在Winform窗体中使用WPF控件(附源码)

    原文:在Winform窗体中使用WPF控件(附源码) 今天是礼拜6,下雨,没有外出,闲暇就写一篇博文讲下如何在Winform中使用WPF控件.原有是我在百度上搜索相关信息无果,遂干脆动手自己实现. W ...

  3. WinForm开发中针对TreeView控件改变当前选择节点的字体与颜色

    本文转载:http://www.cnblogs.com/umplatform/archive/2012/08/29/2660240.html 在B/S开发中,对TreeView控件要改变当前选中节点的 ...

  4. C#里WinForm开发中如何实现控件随窗体大小的改变而自动适应其改变(转)

    在设计可供用户调整大小的窗体时,如何实现该窗体上的控件也应能正确地随窗体的改变而自动调整大小并且能重新定位?此时就要借助控件的.Anchor属性.Anchor属性定义控件的定位点位置.当控件锚定到某个 ...

  5. Windows编程中各种操作文件的方法

    windows编程中文件操作有以下几种常见方法:1.C语言中文件操作.2.C++语言中的文件操作.3.Win32 API函数文件操作.4.MFC CFile类文件操作.5.MFC CFileDialo ...

  6. C# WinForm程序中使用Unity3D控件 (转)

    https://www.cnblogs.com/cnxkey/articles/5394378.html 最近在自学Unity3D,打算使用这个时髦.流行.强大的游戏引擎开发一个三维业务展示系统,不过 ...

  7. winform自定义控件中其他遮挡控件点击事件

    自定义控件在其他窗口调用时,里面的lable阻挡了控件的点击事件 解决方法 自定义控件中lable的 点击事件 private void Lable1_Click(object sender, Eve ...

  8. QTP描述性编程中往WebEdit控件输入文字问题

    在网上查找到许多相关的描述性编程的案例,自己就想动手一试,于是在专家视图中输入如下代码: systemUtil.Run "http://www.baidu.com" wait(15 ...

  9. WinForm中跨线程操作控件

    在WinForm编程时会遇到通过后台线程操作界面的情况,直接在后台线程执行的方法中直接操作控件会报错,这时候就要使用跨线程方式间接操作控件.下面是两种实现方式.   1.采用定义delegate的方式 ...

随机推荐

  1. poj 2104 K-th Number(主席树 视频)

    K-th Number 题意: 给你一些数,让你求一个区间内,第k大的数是多少. 题解: 主席树第一题,看的qsc视频写的,戳戳戳 学到了unique函数,他的作用是:把相邻的重复的放到后面,返回值是 ...

  2. POJ 1066 Treasure Hunt(计算几何)

    题意:给出一个100*100的正方形区域,通过若干连接区域边界的线段将正方形区域分割为多个不规则多边形小区域,然后给出宝藏位置,要求从区域外部开辟到宝藏所在位置的一条路径,使得开辟路径所需要打通的墙壁 ...

  3. 大神:python怎么爬取js的页面

    大神:python怎么爬取js的页面 可以试试抓包看看它请求了哪些东西, 很多时候可以绕过网页直接请求后面的API 实在不行就上 selenium (selenium大法好) selenium和pha ...

  4. 冲突--ListView与ScrollView冲突的4种解决方案

    众所周知ListView与ScrollView都具有滚动能力,对于这样的View控件,当ScrollView与ListView相互嵌套会成为一种问题: 问题一:ScrollView与ListView嵌 ...

  5. Configuration problem: Only one AsyncAnnotationBeanPostProcessor may exist within the context.

    去配置文件中找 , 某个配置文件被引用了两次以上.移除后保留一个即可.如下即可产生上述问题 <import resource="classpath:testContext-curren ...

  6. Mac 10.10下安装MySQL5.6.21提示安装失败

    只要要在安装的第三步在自定里不要选Startup item就可以了

  7. 如何让div水平居中

    代码实例: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...

  8. EL表达式介绍

    EL 全名为Expression Language EL 语法很简单,它最大的特点就是使用上很方便.接下来介绍EL主要的语法结构: ${sessionScope.user.sex} 所有EL都是以${ ...

  9. 利用 Gitbook 生成文档中心站点

    经过一个多月,Bugtags 最近上线了自己的文档站点:docs.bugtags.com,在这里你可以找到 Bugtags 集成.使用相关的绝大部分问题. 在这之前我们使用的是第三方提供的帮助中心产品 ...

  10. ruby-rails 环境搭建

    https://ruby-china.org/wiki/install_ruby_guide