Winfrom 如何安全简单的跨线程更新控件
来源:http://www.cnblogs.com/rainbowzc/archive/2010/09/29/1838788.html
由于多线程可能导致对控件访问的不一致,导致出现问题。C#中默认是要线程安全的,即在访问控件时需要首先判断是否跨线程,如果是跨线程的直接访问,在运行时会抛出异常。
解决办法有两个:
1、不进行线程安全的检查
2、通过委托的方式,在控件的线程上执行
常用写法:(不安全)
private void WriteToolStripMsg(string msg, Color color)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new MethodInvoker(delegate()
{
toolStripMsg.Text = msg;
toolStripMsg.ForeColor = color; }));
}
else
{
toolStripMsg.Text = msg;
toolStripMsg.ForeColor = color;
}
} private void btnLogin_Click(object sender, EventArgs e)
{ string userName = this.txtUserName.Text.Trim();
string pwd = this.txtPwd.Text.Trim(); if (userName.IsNullOrEmpty())
{
WriteToolStripMsg("请输入登录名...", Color.Red);
this.txtUserName.Focus();
return;
}
if (pwd.IsNullOrEmpty())
{
WriteToolStripMsg("请输入密码...", Color.Red);
this.txtPwd.Focus();
return;
} if (userName.IsNotEmpty() && pwd.IsNotEmpty())
{
WriteToolStripMsg("系统正在登陆中...", Color.Blue);
this.btnLogin.BtnEnabled = false;
string msg = string.Empty;
Thread t = new Thread(() =>
{
//判断用户登录是否成功。
string restulMsg = string.Empty;
restulMsg = DataCenterService.Instance.Login(userName, pwd);
if (restulMsg.IsNullOrEmpty())
{
SysUser.CurrUserEntity = DataCenterService.Instance.GetInfoForName(userName);
this.DialogResult = DialogResult.OK;
}
else
{
WriteToolStripMsg(restulMsg, Color.Red);
this.BeginInvoke(new MethodInvoker(delegate()
{
this.btnLogin.BtnEnabled = true;
}));
}
});
t.IsBackground = true;
t.Start();
}
}
上述写法并不是最安全的,存在一定的问题。
推荐写法:
delegate void UpdateShowInfoDelegate(System.Windows.Forms.TextBox txtInfo, string Info);
/// <summary>
/// 显示信息
/// </summary>
/// <param name="txtInfo"></param>
/// <param name="Info"></param>
public void ShowInfo(System.Windows.Forms.TextBox txtInfo, string Info)
{
if (this.InvokeRequired)
{
//this.BeginInvoke(new MethodInvoker(delegate()
//{
// txtInfo.AppendText(Info);
// txtInfo.AppendText(Environment.NewLine + "\r\n");
// txtInfo.ScrollToCaret();
//}));
Invoke(new UpdateShowInfoDelegate(ShowInfo), txtInfo,Info);
return;
}
else
{
txtInfo.AppendText(Info);
txtInfo.AppendText(Environment.NewLine + "\r\n");
txtInfo.ScrollToCaret();
}
}
How to update the GUI from another thread in C#?
本文转载:http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c
跨线程时使用静态扩展方法更新控件
在CodeProject上看一个跨线程更新的方法,备忘一下。
如果在应用中存在较多简单的跨线程操作,下面的方法可能比较实用:
public static class ExtensionMethod
{
/// <summary>
/// 有返回值的扩展方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TResult"></typeparam>
/// <param name="isi"></param>
/// <param name="call"></param>
/// <returns></returns>
public static TResult SafeInvoke<T, TResult>(this T isi, Func<T, TResult> call) where T : ISynchronizeInvoke
{
if (isi.InvokeRequired) {
IAsyncResult result = isi.BeginInvoke(call, new object[] { isi });
object endResult = isi.EndInvoke(result); return (TResult)endResult;
}
else
return call(isi);
}
/// <summary>
/// 没有返回值的扩展方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="isi"></param>
/// <param name="call"></param>
public static void SafeInvoke<T>(this T isi, Action<T> call) where T : ISynchronizeInvoke
{
if (isi.InvokeRequired) isi.BeginInvoke(call, new object[] { isi });
else
call(isi);
}
}
然后在使用时就可以使用匿名委托很方便的操作:
lblProcent.SafeInvoke(d => d.Text = textForLabel);
progressBar1.SafeInvoke(d => d.Value = i);string labelText = lblProcent.SafeInvoke(d => d.Text);静态的扩展类方法使用泛型模板扩展像所有可继承 ISynchronizeInvoke 接口的控件,几乎适用于常见的所有控件呦 (来自 CodeProject 为所有类型的更新创建异步委托)
原始地址:http://www.codeproject.com/Articles/52752/Updating-Your-Form-from-Another-Thread-without-Cre
Winfrom 如何安全简单的跨线程更新控件的更多相关文章
- C#跨线程操作控件的最简单实现探究
随着程序复杂度的提高,程序不可避免会出现多个线程,此时就很可能存在跨线程操作控件的问题. 跨线程操作UI控件主要有三类方式: 1.禁止系统的线程间操作检查.(此法不建议使用) 2.使用Invoke(同 ...
- C# WinFrom 跨线程访问控件
1.跨线程访问控件委托和类的定义 using System; using System.Windows.Forms; namespace ahwildlife.Utils { /// <summ ...
- C# 跨线程调用控件
在C# 的应用程序开发中, 我们经常要把UI线程和工作线程分开,防止界面停止响应. 同时我们又需要在工作线程中更新UI界面上的控件, 下面介绍几种常用的方法 阅读目录 线程间操作无效 第一种办法:禁 ...
- 【转载】C# 跨线程调用控件
转自:http://www.cnblogs.com/TankXiao/p/3348292.html 感谢原作者,转载以备后用 在C# 的应用程序开发中, 我们经常要把UI线程和工作线程分开,防止界面停 ...
- C# 跨线程调用控件的4中方法
原文:C# 跨线程调用控件 在C# 的应用程序开发中, 我们经常要把UI线程和工作线程分开,防止界面停止响应. 同时我们又需要在工作线程中更新UI界面上的控件, 下面介绍几种常用的方法 阅读目录 线 ...
- winform跨线程访问控件
首先说下,.net 2.0以后加强了安全机制,不允许在winform中直接跨线程访问控件的属性.所以除了控件所在的线程外的线程调用会抛异常 (Cross-thread operation not va ...
- C# 跨线程对控件赋值
第一种 跨线程对控件赋值 private void button2_Click(object sender, EventArgs e) { Thread thread1 = new Thread(ne ...
- C# 跨线程访问控件(MethodInvoker)
参考:https://www.cnblogs.com/lvdongjie/p/5428815.html .Net 通常禁止跨线程访问控件,设置Control.CheckForIllegalCrossT ...
- WinForm中新开一个线程操作 窗体上的控件(跨线程操作控件)
最近在做一个winform的小软件(抢票的...).登录窗体要从远程web页面获取一些数据,为了不阻塞登录窗体的显示,开了一个线程去加载数据远程的数据,会报一个错误"线程间操作无效: 从不是 ...
随机推荐
- 查看Oracle表空间使用情况与增大表空间
1,查看表空间使用情况 SELECT D.TABLESPACE_NAME, SPACE || 'M' "SUM_SPACE(M)", BLOCKS "SUM_BLOCKS ...
- 【译】4个你需要知道的Asset Catalog的秘密
本文由CocoaChina译者 @唧唧歪歪 翻译,作者:Hector Matos 原文:4 XCODE ASSET CATALOG SECRETS YOU NEED TO KNOW 恶梦 想象你正在干 ...
- SORT_AREA_RETAINED_SIZE
manual pga: SORT_AREA_RETAINED_SIZE specifies (in bytes) the maximum amount of the user global area ...
- VS2012 独占编辑 设置
用VS2008建立的项目就有(禁止其他用户签出和签入) 为什么VS2012的项目就没有了呢??(管理员说他什么都没设置)VS2012: 两个项目同样是用VS2012打开的,而第一个是用VS2008创建 ...
- 在使用MOS管时要注意的问题
1.当Vds电压增大,Ciss增大,栅极充放电电流也会增大 2.MOS管的功率损耗要控制在额定功耗以下 3.在Buck电路中,开关MOS管的Vds在MOS管关断时会非常大
- Android Camera 预览图像被拉伸变形的解决方法【转】
问题描述: 预览图像被拉伸变形 问题原因: 由于预览图像大小跟SurfaceView 大小不一致引起 解决方法: 获取系统支持的所有预览尺寸[getSupportedPictureSizes],然后再 ...
- 关于BootStrap下图标的显示问题
我现在在做自己的毕业设计,用到了bootstrap的这一套css样式,说句心里话,这一套东西确实很好用,但是一个小问题足足浪费了我将近两个小时. 我的问题是:没有办法使用bootstrap下的图标(很 ...
- bzoj 2401: 陶陶的难题I 数论
2401: 陶陶的难题I Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 89 Solved: 24[Submit][Status] Descript ...
- 形形色色Node工程Angular2
最近项目要用的 一些无关紧要的文件夹, demo是一些示例, dist是webpack打包后发布的代码,server是用node启动服务,typings和tsconfig是一些ts配置. npm in ...
- Ansj分词双数组Trie树实现与arrays.dic词典格式
http://www.hankcs.com/nlp/ansj-word-pairs-array-tire-tree-achieved-with-arrays-dic-dictionary-format ...