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页面获取一些数据,为了不阻塞登录窗体的显示,开了一个线程去加载数据远程的数据,会报一个错误"线程间操作无效: 从不是 ...
随机推荐
- 【bzoj】1026: [SCOI2009]windy数
1026: [SCOI2009]windy数 Description windy定义了一种windy数.不含前导零且相邻两个数字之差至少为2的正整数被称为windy数. windy想知道,在A和B之间 ...
- 向OC类中添加默认的协议实现(ProtocolKit)
以forkingdog的PorotocolKit举例 举例 ProtocolKit Protocol extension for Objective-C Usage Your protocol: @p ...
- 欧几里得旅行商问题 java与c++实现
双调欧几里得旅行商问题是一个经典动态规划问题.<算法导论(第二版)>思考题15-1 旅行商问题描述:平面上n个点,确定一条连接各点的最短闭合旅程.这个解的一般形式为NP的(在多项式时间内可 ...
- Discuz帖子列表页无法ajax加载下一页问题
上周末抽空重构了一下JX3PVE的PVE栏目,只上线了宏库栏目,结果出了一堆Bug.奈何公司这段时间都在搞完美假期这专题,太忙也没去处理.这不是周末拿时间来看一下. 发现其中有一个是点“下一页”aja ...
- servlet 默认是线程安全的吗?
由于Servlet默认是以多线程模式执行的,所以,在编写代码时需要非常细致地考虑多线程的安全问题.然而,很多人编写Servlet程序时并没 有注意到多线程安全的问题,这往往造成编写的程序在少量用户访问 ...
- complex(x):创建一个复数
使用python可以实现将一个整数或者浮点数转换为一个复数: 演示如下: >>> # 演示复数函数:complex(x) ... >>> x = complex(1 ...
- 解决cocos2d-X 2.0版本后创建的Android项目提示org.cocos2dx.lib.Cocos2dxActivity找不到问题
原地址: http://blog.163.com/zhoulong19880518@126/blog/static/6070970220132511558143/ 解决方法: 复制 ***\co ...
- Serv-u FTP服务器
它可以让我们通过http协议(web端)或者通过其他软件进行连接,从而可以操作服务器上的文件数据.
- 一个优秀的http实现框架
package com.ming; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unir ...
- 在网页中插入CSS样式表的几种方法
1. 链入外部样式表 链入外部样式表是把样式表保存为一个样式表文件,然后在页面中用<link>标记链接到这个样式表文件,这个<link>标记必须放到页面的<head> ...