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. Calculations are rather interesting

    Calculations are rather interesting, especially when some thoughts are involved therein.

  2. webview--网络超时

    package com.test.js2java; import java.util.Timer; import java.util.TimerTask; import android.app.Act ...

  3. ylbtech-Bill(发票管理)-数据库设计

    ylbtech-dbs:ylbtech-Bill(发票管理)-数据库设计 -- =============================================-- DatabaseName ...

  4. Ubuntu配置网络命令(转载)

    From:http://blog.csdn.net/ithomer/article/details/6264881 以eth0为例   1. 以DHCP方式配置网卡 编辑文件: /etc/networ ...

  5. Mysql设置字符编码及varchar宽度问题

    ubuntu16.04通过仓库安装的mysql5.7的配置文件在 /etc/mysql/mysql.conf.d/mysqld.cnf 修改字符只需要 在[mysqld] character-set- ...

  6. [ActionScript 3.0] AS3 深入理解Flash的 应用程序域Application Domains

    简介 网上有很多flash,通常都不需要显示的使用应用程序域,因为默认的应用程序域就够用了.其实复杂的情况下需要用到应用程序域,比如说有两个不同的swf,一个是旧版本的,一个是新版的,这两个文件里的类 ...

  7. turing 项目引用

    1.友盟自动更新 2.友盟统计 3.友盟消息推送 http://www.bejson.com/json2javapojo/ 引用bejson 解析JSON生成类,数组 private List< ...

  8. django 模板if判断的时候==两边需要有空格

    比如 {%if a=='y'%}错误,{%if a =='y'%}也是错误的 只能是{%if a == 'y'%}这样才行

  9. ACM—最大连续子序列(HDOJ1003)

    HDOJ链接 http://acm.hdu.edu.cn/showproblem.php?pid=1003 不了解题目的朋友可以先看一下题目,在这里就不再详细介绍了.(文章内容和解题思路不完全相同,方 ...

  10. poj 2632 Crashing Robots

    点击打开链接 Crashing Robots Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 6655   Accepted: ...