1.第一种,不安全,当线程过多后,timer控件和线程中同时访问窗体控件时,有时会出现界面重绘出错。

  1. public frmMain()
    {
    InitializeComponent();
    System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls =false;
    }

2.避免繁复的delegate,Invoke,转载,不推荐使用

  1. public static class ControlCrossThreadCalls
  2. {
  3. public delegate void InvokeHandler();
  4.  
  5. ///<summary>
  6. /// 线程安全访问控件,扩展方法 .net 3.5下用Lambda简化跨线程访问窗体控件,避免繁复的delegate,Invoke
  7. /// this.SafeInvoke(() =>
  8. /// {
  9. /// tsStatus.Text = one.Email + " 开始任务....";
  10. /// });
  11. ///</summary>
  12. //public static void SafeInvoke(this Control control, InvokeHandler handler)
  13. //{
  14. // if (control.InvokeRequired)
  15. // {
  16. // control.Invoke(handler);
  17. // }
  18. // else
  19. // {
  20. // handler();
  21. // }
  22. //}
  23.  
  24. ///<summary>
  25. /// .net2.0线程安全访问扩展方法///</summary>
  26. /// ControlCrossThreadCalls.SafeInvoke(this.tsStatus, new ControlCrossThreadCalls.InvokeHandler(delegate()
  27. /// {
  28. /// tsStatus.Text = one.Email + " 开始任务...";
  29. /// }));
  30. public static void SafeInvoke(Control control, InvokeHandler handler)
  31. {
  32. if (control.InvokeRequired)
  33. {
  34. control.Invoke(handler);
  35. }
  36. else
  37. {
  38. handler();
  39. }
  40. }
  41. }

3.异步最新,推荐使用

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Threading;
  6.  
  7. /// <summary>
  8. /// 线程中安全访问控件,避免重复的delegate,Invoke
  9. /// </summary>
  10. public static class CrossThreadCalls
  11. {
  12. public delegate void TaskDelegate();
  13.  
  14. private delegate void InvokeMethodDelegate(Control control, TaskDelegate handler);
  15.  
  16. /// <summary>
  17. /// .net2.0中线程安全访问控件扩展方法,可以获取返回值,可能还有其它问题
  18. /// </summary>
  19. /// CrossThreadCalls.SafeInvoke(this.statusStrip1, new CrossThreadCalls.TaskDelegate(delegate()
  20. /// {
  21. /// tssStatus.Text = "开始任务...";
  22. /// }));
  23. /// CrossThreadCalls.SafeInvoke(this.rtxtChat, new CrossThreadCalls.TaskDelegate(delegate()
  24. /// {
  25. /// rtxtChat.AppendText("测试中");
  26. /// }));
  27. /// 参考:http://wenku.baidu.com/view/f0b3ac4733687e21af45a9f9.html
  28. /// <summary>
  29. public static void SafeInvoke(Control control, TaskDelegate handler)
  30. {
  31. if (control.InvokeRequired)
  32. {
  33. while (!control.IsHandleCreated)
  34. {
  35. if (control.Disposing || control.IsDisposed)
  36. return;
  37. }
  38. IAsyncResult result = control.BeginInvoke(new InvokeMethodDelegate(SafeInvoke), new object[] { control, handler });
  39. control.EndInvoke(result);//获取委托执行结果的返回值
  40. return;
  41. }
  42. IAsyncResult result2 = control.BeginInvoke(handler);
  43. control.EndInvoke(result2);
  44. }
  45.  
  46. /// <summary>
  47. /// 线程安全访问控件,扩展方法.net3.5用Lambda简化跨线程访问窗体控件,避免重复的delegate,Invoke
  48. /// this.statusStrip1.SafeInvoke(() =>
  49. /// {
  50. /// tsStatus.Text = "开始任务....";
  51. /// });
  52. /// this.rtxtChat.SafeInvoke(() =>
  53. /// {
  54. /// rtxtChat.AppendText("测试中");
  55. /// });
  56. /// </summary>
  57. //public static void SafeInvoke(this Control control, TaskDelegate handler)
  58. //{
  59. // if (control.InvokeRequired)
  60. // {
  61. // while (!control.IsHandleCreated)
  62. // {
  63. // if (control.Disposing || control.IsDisposed)
  64. // return;
  65. // }
  66. // IAsyncResult result = control.BeginInvoke(new InvokeMethodDelegate(SafeInvoke), new object[] { control, handler });
  67. // control.EndInvoke(result);//获取委托执行结果的返回值
  68. // return;
  69. // }
  70. // IAsyncResult result2 = control.BeginInvoke(handler);
  71. // control.EndInvoke(result2);
  72. //}

更正一个我发现的C#多线程安全访问控件普遍存在的问题,仅供参考,在网上搜索多线程访问控件,发现很多都是这种类似的写法

http://msdn.microsoft.com/zh-cn/library/ms171728.aspx

  1. private void SetText(string text)
  2. {
  3. // InvokeRequired required compares the thread ID of the
  4. // calling thread to the thread ID of the creating thread.
  5. // If these threads are different, it returns true.
  6. if (this.textBox1.InvokeRequired)
  7. {
  8. SetTextCallback d = new SetTextCallback(SetText);
  9. this.Invoke(d, new object[] { text });
  10. }
  11. else
  12. {
  13. this.textBox1.Text = text;
  14. }
  15. }

注意红色部分,这样写几个线程同时操作时问题不是很大,但是当我几10个几100个线程频繁操作时,就出现了System.OutOfMemoryException这个异常,猜测可能是线程堵塞,同时造成cpu很高,内存成倍增长。

C#线程中安全访问控件(重用委托,避免繁复的delegate,Invoke)总结的更多相关文章

  1. C#学习之在辅助线程中修改UI控件----invoke方法

    Invoke and BeginInvoke 转载地址:http://www.cnblogs.com/worldreason/archive/2008/06/09/1216127.html 在Invo ...

  2. C#中禁止跨线程直接访问控件

    C#中禁止跨线程直接访问控件,InvokeRequired是为了解决这个问题而产生的,当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它.此时它将会在内部调用ne ...

  3. [C#] Control.Invoke方法和跨线程访问控件(转载)

    转载前,在网上找了好多INVOKE方法的文章,就这个看着还可以,明白了大概,以后再深用的时候再研究 ,废话少说上转载(连转载都说的这么有气势,哈哈)   在设计界面时,我们经常需要将一些需要时间才能完 ...

  4. C#中跨线程访问控件问题解决方案

    net 原则上禁止跨线程访问控件,因为这样可能造成错误的发生,推荐的解决方法是采用代理,用代理方法来间接操作不是同一线程创建的控件. 第二种方法是禁止编译器对跨线程访问作检查,可以实现访问,但是出不出 ...

  5. [C#] Control.Invoke方法和跨线程访问控件

    在设计界面时,我们经常需要将一些需要时间才能完成的操作放在另一个线程(不同于UI主线程)中执行.但是这些操作可能需要将其结果或完成情况通知主线程,比如调用窗体的方法,或者触发事件(由界面响应事件),很 ...

  6. C#之Winform跨线程访问控件

    C#中禁止跨线程直接访问控件,InvokeRequired是为了解决这个问题而产生的,当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它.此时它将会在内部调用ne ...

  7. C#中跨线程访问控件

    net 原则上禁止跨线程访问控件,因为这样可能造成错误的发生,推荐的解决方法是采用代理,用代理方法来间接操作不是同一线程创建的控件. 第二种方法是禁止编译器对跨线程访问作检查,可以实现访问,但是出不出 ...

  8. c#跨线程访问控件帮助类

    1.背景 对于winform程序来说,当我们点击按钮,需要消耗一定时长才能拿到数据后才能显示在界面上某个控件上的情况,我们通常会专门开一个线程去拿数据,这样不会造成界面处于假死状态 2.常规做法 // ...

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

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

随机推荐

  1. mysql两种备份方法总结:mysqldump 和 xtrabackup

    mysqldump工具基本使用 1. mysqldump [OPTIONS] database [tables…] 还原时库必须存在,不存在需要手动创建     --all-databases: 备份 ...

  2. 自定义UICollectionViewLayout

    UICollectionView在iOS6中第一次被介绍,也是UIKit视图类中的一颗新星.它和UITableView共享API设计,但也在UITableView上做了一些扩展.UICollectio ...

  3. Docker 安装、卸载、启动、停止

    1.1 查看当前系统的内核版本 查看当前系统的内核版本是否高于 3.10 英文文档:https://docs.docker.com/ 中文文档:https://docs.docker-cn.com/  ...

  4. 网络层ddos与应用层ddos区别

    以去银行办业务举例: 网络层ddos是让去往银行的道路交通变得拥堵,无法使正真要去银行的人到达:常利用协议为网络层的,如tcp(利用三次握手的响应等待及电脑tcp连接数限制)等 应用层ddos则是在到 ...

  5. debian利用snmp监控服务器异常状态

    1.安装snmp apt-get install snmp snmpd 2.配置snmp vi /etc/snmp/snmpd.conf 注释15行 #agentAddress udp:127.0.0 ...

  6. Uva 10635 - Prince and Princess LCS/LIS

    两个长度分别为p+1和q+1的由1到n2之前的整数组成的序列,每个序列的元素各不相等,两个序列第一个元素均为1.求两个序列的最长公共子序列 https://uva.onlinejudge.org/in ...

  7. 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 ...

  8. 超好用的input模糊搜索 jq模糊搜索,

    上来先展示效果:默认展示效果: 输入内容: 上代码: css部分: <style type="text/css"> * { padding:; margin:; } h ...

  9. layui 单选框取消选中

    <ul> <li> <span class="time">17:18</span> <span class="typ ...

  10. 微信小程序细节部分

    微信小程序和HTML区别: 1.开发工具不同,H5的开发工具+浏览器Device Mode预览,小程序的开发基于自己的开发者工具 2.开发语言不同,小程序自己开发了一套WXML标签语言和WXSS样式语 ...