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 ...
随机推荐
- ECMAScrip5 二
一.ES5的严格模式 在严格模式下,声明变量必须使用 var 在严格模式下,不能使用八进制 在严格模式下,不能使用arguments.callee 在严格模式下,不能使用eval() //eva ...
- 【 React -- 2/100 】使用React实现评论功能
React| 组件化 | 递归 | 生成唯一ID 需要探究一下 .find() 和 findIndex() 的区别 import React from 'react' import './commen ...
- Mysql逻辑架构介绍
总体概览: 和其它数据库相比,MySQL有点与众不同,它的架构可以在多种不同场景中应用并发挥良好作用.主要体现在存储引擎的架构上,插件式的存储引擎架构将查询处理和其它的系统任务以及数据的存储提取相分离 ...
- MyBatis中返回List
一般情况下,我们需要返回一个List 在Dao层定义: List<TbAddress> selectAll(); 那么在对应的mapper文件中,应该如下: <select id=& ...
- VB中IIF函数
IIf 函数语法:IIf(表达式, 真值部分, 假值部分)根据表达式的值,表达式为真时,返回真值部分,表达式为假时,返回假部分.如:iif(a>0, "对","错& ...
- 生成对抗网络资源 Adversarial Nets Papers
来源:https://github.com/zhangqianhui/AdversarialNetsPapers AdversarialNetsPapers The classical Papers ...
- string初始化
#include <iostream> using namespace std; int main(int argc, const char * argv[]) { //通过const c ...
- memcpy函数的用法以及实现一个memcpy函数
memcpy的用法 在项目中经常用到memcpy来实现内存的拷贝工作,如下代码片段 memcpy( pData, m_pSaveData_C, iSize * sizeof( unsigned sho ...
- 【Linux】CentOS6上安装Python3.7(config、make、make install)及“No module named '_ctypes'”/pip install时“ssl module in Python is not available.”的解决
1.下载安装包 https://www.python.org/ftp/python/ 该目录下选择所需要的版本进行下载.解压. wget https://www.python.org/ftp/pyth ...
- Mac下Sublime text3无法安装Package Control及中文乱码问题
sublime text3是一款轻量级的代码编辑器,我曾在Windows下配置过,但时间久了就忘了.这次是在mac上配置,在网上查了一些帖子,有的叙述不是很清楚,故记录一下详细过程. 在线安装: ht ...