来源: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

也可以参考:http://www.codeproject.com/Articles/37413/A-Generic-Method-for-Cross-thread-Winforms-Access#xx3867544xx

Winfrom 如何安全简单的跨线程更新控件的更多相关文章

  1. C#跨线程操作控件的最简单实现探究

    随着程序复杂度的提高,程序不可避免会出现多个线程,此时就很可能存在跨线程操作控件的问题. 跨线程操作UI控件主要有三类方式: 1.禁止系统的线程间操作检查.(此法不建议使用) 2.使用Invoke(同 ...

  2. C# WinFrom 跨线程访问控件

    1.跨线程访问控件委托和类的定义 using System; using System.Windows.Forms; namespace ahwildlife.Utils { /// <summ ...

  3. C# 跨线程调用控件

    在C# 的应用程序开发中, 我们经常要把UI线程和工作线程分开,防止界面停止响应.  同时我们又需要在工作线程中更新UI界面上的控件, 下面介绍几种常用的方法 阅读目录 线程间操作无效 第一种办法:禁 ...

  4. 【转载】C# 跨线程调用控件

    转自:http://www.cnblogs.com/TankXiao/p/3348292.html 感谢原作者,转载以备后用 在C# 的应用程序开发中, 我们经常要把UI线程和工作线程分开,防止界面停 ...

  5. C# 跨线程调用控件的4中方法

    原文:C# 跨线程调用控件 在C# 的应用程序开发中, 我们经常要把UI线程和工作线程分开,防止界面停止响应.  同时我们又需要在工作线程中更新UI界面上的控件, 下面介绍几种常用的方法 阅读目录 线 ...

  6. winform跨线程访问控件

    首先说下,.net 2.0以后加强了安全机制,不允许在winform中直接跨线程访问控件的属性.所以除了控件所在的线程外的线程调用会抛异常 (Cross-thread operation not va ...

  7. C# 跨线程对控件赋值

    第一种 跨线程对控件赋值 private void button2_Click(object sender, EventArgs e) { Thread thread1 = new Thread(ne ...

  8. C# 跨线程访问控件(MethodInvoker)

    参考:https://www.cnblogs.com/lvdongjie/p/5428815.html .Net 通常禁止跨线程访问控件,设置Control.CheckForIllegalCrossT ...

  9. WinForm中新开一个线程操作 窗体上的控件(跨线程操作控件)

    最近在做一个winform的小软件(抢票的...).登录窗体要从远程web页面获取一些数据,为了不阻塞登录窗体的显示,开了一个线程去加载数据远程的数据,会报一个错误"线程间操作无效: 从不是 ...

随机推荐

  1. qt 5 基础知识 2(控件篇)

    QVBoxLayout *lay = new QVBoxLayout(this); // 创建一个竖直的盒子 lebel 篇 lay->addWidget(label = new QLabel( ...

  2. DJANGO:根据不同的环境,配置不同的SETTINGS文件,读取不同的DB,JENKINS,SALT配置

    今天撸了一次,实现如下: 1,新建配置目录,将不同的环境的SETTINGS.PY文件独立出来,并将各自环境引用的DB连接,JENKINS,SALT等参数都写在里面. DEMO: JENKINS = { ...

  3. CAS实现单点登录方案(SSO完整版)

    一.简介 1.cas是由耶鲁大学研发的单点登录服务器 2.本教材所用环境 Tomcat7.2 JDK1.7 CAS Service 版本    cas-server-3.4.8-release CAS ...

  4. UVA 11426 GCD Extrme (Ⅲ)

    给定一个整数N(1<N<=4000000)的整数求∑GCD(i,j)i=1,2,3....j-1,2<=j<=n的值.参考了一下网上的题解,复述一下我理解后的思路,加深理解: ...

  5. dump datafile block

    Oracle dump datafile block有两种方式: 然后根据block id执行dump 命令: SQL> alter system dump datafile 4 block 2 ...

  6. java学习之线程

    一.线程总述: 线程是java当中一个重要的内容,如果想说线程的话,那我们应该先来讲一下什么是进程. 进程:那么什么是进程呢,进程从字面上来理解就是,正在进行的程序.就比如说我们在windows当中打 ...

  7. [C# 网络编程系列]专题七:UDP编程补充——UDP广播程序的实现

    转自:http://www.cnblogs.com/zhili/archive/2012/09/03/2666974.html 上次因为时间的关系,所以把上一个专题遗留下的一个问题在本专题中和大家分享 ...

  8. HDU-2568 前进

    http://acm.hdu.edu.cn/showproblem.php?pid=2568 前进 Time Limit: 2000/1000 MS (Java/Others)    Memory L ...

  9. Oracle11g客户端for centos 5.5安装文档

    前提:安装centos的时候,最好把系统的所有的安装包都安装上.以下命令需手动输入,不要复制粘贴. 1.以root用户登录centos5.5的操作系统:创建oracle用户组和用户. groupadd ...

  10. "The Same Game": A Simple Game from Start to Finish

    文档视图结构 文档/视图体系结构是一个神奇的架构,通过这个架构,我们可以分离应用程序的数据和显示.文档包含了全部的数据,视图从文档获取数据并且显示给用户.针对这个游戏例子,我们得数据是游戏板和有颜色的 ...