C#线程中安全访问控件(重用委托,避免繁复的delegate,Invoke)总结
1.第一种,不安全,当线程过多后,timer控件和线程中同时访问窗体控件时,有时会出现界面重绘出错。
- public frmMain()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls =false;
}
2.避免繁复的delegate,Invoke,转载,不推荐使用

- public static class ControlCrossThreadCalls
- {
- public delegate void InvokeHandler();
- ///<summary>
- /// 线程安全访问控件,扩展方法 .net 3.5下用Lambda简化跨线程访问窗体控件,避免繁复的delegate,Invoke
- /// this.SafeInvoke(() =>
- /// {
- /// tsStatus.Text = one.Email + " 开始任务....";
- /// });
- ///</summary>
- //public static void SafeInvoke(this Control control, InvokeHandler handler)
- //{
- // if (control.InvokeRequired)
- // {
- // control.Invoke(handler);
- // }
- // else
- // {
- // handler();
- // }
- //}
- ///<summary>
- /// .net2.0线程安全访问扩展方法///</summary>
- /// ControlCrossThreadCalls.SafeInvoke(this.tsStatus, new ControlCrossThreadCalls.InvokeHandler(delegate()
- /// {
- /// tsStatus.Text = one.Email + " 开始任务...";
- /// }));
- public static void SafeInvoke(Control control, InvokeHandler handler)
- {
- if (control.InvokeRequired)
- {
- control.Invoke(handler);
- }
- else
- {
- handler();
- }
- }
- }

3.异步最新,推荐使用

- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading;
- /// <summary>
- /// 线程中安全访问控件,避免重复的delegate,Invoke
- /// </summary>
- public static class CrossThreadCalls
- {
- public delegate void TaskDelegate();
- private delegate void InvokeMethodDelegate(Control control, TaskDelegate handler);
- /// <summary>
- /// .net2.0中线程安全访问控件扩展方法,可以获取返回值,可能还有其它问题
- /// </summary>
- /// CrossThreadCalls.SafeInvoke(this.statusStrip1, new CrossThreadCalls.TaskDelegate(delegate()
- /// {
- /// tssStatus.Text = "开始任务...";
- /// }));
- /// CrossThreadCalls.SafeInvoke(this.rtxtChat, new CrossThreadCalls.TaskDelegate(delegate()
- /// {
- /// rtxtChat.AppendText("测试中");
- /// }));
- /// 参考:http://wenku.baidu.com/view/f0b3ac4733687e21af45a9f9.html
- /// <summary>
- public static void SafeInvoke(Control control, TaskDelegate handler)
- {
- if (control.InvokeRequired)
- {
- while (!control.IsHandleCreated)
- {
- if (control.Disposing || control.IsDisposed)
- return;
- }
- IAsyncResult result = control.BeginInvoke(new InvokeMethodDelegate(SafeInvoke), new object[] { control, handler });
- control.EndInvoke(result);//获取委托执行结果的返回值
- return;
- }
- IAsyncResult result2 = control.BeginInvoke(handler);
- control.EndInvoke(result2);
- }
- /// <summary>
- /// 线程安全访问控件,扩展方法.net3.5用Lambda简化跨线程访问窗体控件,避免重复的delegate,Invoke
- /// this.statusStrip1.SafeInvoke(() =>
- /// {
- /// tsStatus.Text = "开始任务....";
- /// });
- /// this.rtxtChat.SafeInvoke(() =>
- /// {
- /// rtxtChat.AppendText("测试中");
- /// });
- /// </summary>
- //public static void SafeInvoke(this Control control, TaskDelegate handler)
- //{
- // if (control.InvokeRequired)
- // {
- // while (!control.IsHandleCreated)
- // {
- // if (control.Disposing || control.IsDisposed)
- // return;
- // }
- // IAsyncResult result = control.BeginInvoke(new InvokeMethodDelegate(SafeInvoke), new object[] { control, handler });
- // control.EndInvoke(result);//获取委托执行结果的返回值
- // return;
- // }
- // IAsyncResult result2 = control.BeginInvoke(handler);
- // control.EndInvoke(result2);
- //}

更正一个我发现的C#多线程安全访问控件普遍存在的问题,仅供参考,在网上搜索多线程访问控件,发现很多都是这种类似的写法
http://msdn.microsoft.com/zh-cn/library/ms171728.aspx

- private void SetText(string text)
- {
- // InvokeRequired required compares the thread ID of the
- // calling thread to the thread ID of the creating thread.
- // If these threads are different, it returns true.
- if (this.textBox1.InvokeRequired)
- {
- SetTextCallback d = new SetTextCallback(SetText);
- this.Invoke(d, new object[] { text });
- }
- else
- {
- this.textBox1.Text = text;
- }
- }

注意红色部分,这样写几个线程同时操作时问题不是很大,但是当我几10个几100个线程频繁操作时,就出现了System.OutOfMemoryException这个异常,猜测可能是线程堵塞,同时造成cpu很高,内存成倍增长。
C#线程中安全访问控件(重用委托,避免繁复的delegate,Invoke)总结的更多相关文章
- C#学习之在辅助线程中修改UI控件----invoke方法
Invoke and BeginInvoke 转载地址:http://www.cnblogs.com/worldreason/archive/2008/06/09/1216127.html 在Invo ...
- C#中禁止跨线程直接访问控件
C#中禁止跨线程直接访问控件,InvokeRequired是为了解决这个问题而产生的,当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它.此时它将会在内部调用ne ...
- [C#] Control.Invoke方法和跨线程访问控件(转载)
转载前,在网上找了好多INVOKE方法的文章,就这个看着还可以,明白了大概,以后再深用的时候再研究 ,废话少说上转载(连转载都说的这么有气势,哈哈) 在设计界面时,我们经常需要将一些需要时间才能完 ...
- C#中跨线程访问控件问题解决方案
net 原则上禁止跨线程访问控件,因为这样可能造成错误的发生,推荐的解决方法是采用代理,用代理方法来间接操作不是同一线程创建的控件. 第二种方法是禁止编译器对跨线程访问作检查,可以实现访问,但是出不出 ...
- [C#] Control.Invoke方法和跨线程访问控件
在设计界面时,我们经常需要将一些需要时间才能完成的操作放在另一个线程(不同于UI主线程)中执行.但是这些操作可能需要将其结果或完成情况通知主线程,比如调用窗体的方法,或者触发事件(由界面响应事件),很 ...
- C#之Winform跨线程访问控件
C#中禁止跨线程直接访问控件,InvokeRequired是为了解决这个问题而产生的,当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它.此时它将会在内部调用ne ...
- C#中跨线程访问控件
net 原则上禁止跨线程访问控件,因为这样可能造成错误的发生,推荐的解决方法是采用代理,用代理方法来间接操作不是同一线程创建的控件. 第二种方法是禁止编译器对跨线程访问作检查,可以实现访问,但是出不出 ...
- c#跨线程访问控件帮助类
1.背景 对于winform程序来说,当我们点击按钮,需要消耗一定时长才能拿到数据后才能显示在界面上某个控件上的情况,我们通常会专门开一个线程去拿数据,这样不会造成界面处于假死状态 2.常规做法 // ...
- C# WinFrom 跨线程访问控件
1.跨线程访问控件委托和类的定义 using System; using System.Windows.Forms; namespace ahwildlife.Utils { /// <summ ...
随机推荐
- mysql两种备份方法总结:mysqldump 和 xtrabackup
mysqldump工具基本使用 1. mysqldump [OPTIONS] database [tables…] 还原时库必须存在,不存在需要手动创建 --all-databases: 备份 ...
- 自定义UICollectionViewLayout
UICollectionView在iOS6中第一次被介绍,也是UIKit视图类中的一颗新星.它和UITableView共享API设计,但也在UITableView上做了一些扩展.UICollectio ...
- Docker 安装、卸载、启动、停止
1.1 查看当前系统的内核版本 查看当前系统的内核版本是否高于 3.10 英文文档:https://docs.docker.com/ 中文文档:https://docs.docker-cn.com/ ...
- 网络层ddos与应用层ddos区别
以去银行办业务举例: 网络层ddos是让去往银行的道路交通变得拥堵,无法使正真要去银行的人到达:常利用协议为网络层的,如tcp(利用三次握手的响应等待及电脑tcp连接数限制)等 应用层ddos则是在到 ...
- debian利用snmp监控服务器异常状态
1.安装snmp apt-get install snmp snmpd 2.配置snmp vi /etc/snmp/snmpd.conf 注释15行 #agentAddress udp:127.0.0 ...
- Uva 10635 - Prince and Princess LCS/LIS
两个长度分别为p+1和q+1的由1到n2之前的整数组成的序列,每个序列的元素各不相等,两个序列第一个元素均为1.求两个序列的最长公共子序列 https://uva.onlinejudge.org/in ...
- AtCoder Beginner Contest 088 C Takahashi's Information
Problem Statement We have a 3×3 grid. A number ci,j is written in the square (i,j), where (i,j) deno ...
- 超好用的input模糊搜索 jq模糊搜索,
上来先展示效果:默认展示效果: 输入内容: 上代码: css部分: <style type="text/css"> * { padding:; margin:; } h ...
- layui 单选框取消选中
<ul> <li> <span class="time">17:18</span> <span class="typ ...
- 微信小程序细节部分
微信小程序和HTML区别: 1.开发工具不同,H5的开发工具+浏览器Device Mode预览,小程序的开发基于自己的开发者工具 2.开发语言不同,小程序自己开发了一套WXML标签语言和WXSS样式语 ...