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

本文探讨了C#中实现线程安全访问UI控件的方法,对比了不同技术手段的效果,并提出了一种适用于大量并发线程场景下的解决方案,以避免内存溢出等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来自:http://www.cnblogs.com/slyzly/articles/2121436.html

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();
        }
    }
}
复制代码

 

更正一个我发现的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很高,内存成倍增长。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值