1.第一种,不安全,时间控件和线程同时访问窗体控件时,有时会出现界面重绘出错。
   public frmMain()
   {
        InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
   }2.避免繁复的delegate,Invoke,推荐,安全/// <summary>
/// 线程中安全访问控件,避免繁复的delegate,Invoke
/// </summary>
public static class ControlCrossThreadCalls
{
    public delegate void InvokeHandler();    /// <summary>
    /// .net2.0线程中安全访问控件扩展方法-事理
    /// </summary>
    /// ControlCrossThreadCalls.SafeInvoke(this,this.statusStrip1, new ControlCrossThreadCalls.InvokeHandler(delegate()
    /// {
    ///    tssStatus.Text = "开始任务...";
    /// }));
    /// ControlCrossThreadCalls.SafeInvoke(this,this.rtxtChat, new ControlCrossThreadCalls.InvokeHandler(delegate()
    /// {
    ///     rtxtChat.AppendText("测试中");
    /// }));
    /// 参考:http://wenku.baidu.com/view/f0b3ac4733687e21af45a9f9.html
    /// <summary>
    public static void SafeInvoke(Form form, Control control, InvokeHandler handler)
    {
        if (control.InvokeRequired)
        {
            form.Invoke(handler);
        }
        else
        {
            handler();
        }
    }    /// <summary>
    /// 线程安全访问控件,扩展方法.net3.5用Lambda简化跨线程访问窗体控件,避免繁复的delegate,Invoke
    /// this.statusStrip1.SafeInvoke(() =>
    /// {
    ///     tsStatus.Text = "开始任务....";
    /// });
    /// this.rtxtChat.SafeInvoke(() =>
    /// {
    ///     rtxtChat.AppendText("测试中");
    /// });
    /// </summary>
    //public static void SafeInvoke(this Control control, InvokeHandler handler)
    //{
    //    if (control.InvokeRequired)
    //    {
    //        control.Invoke(handler);
    //    }
    //    else
    //    {
    //        handler();
    //    }
    //}

解决方案 »

  1.   

    上面的真的有问题。。这样的还好些
    /// <summary>
        /// .net2.0线程中安全访问控件扩展方法-有问题,但是可以获取返回值
        /// </summary>
        /// CrossThreadCalls.SafeInvoke(this,this.statusStrip1, new CrossThreadCalls.InvokeHandler(delegate()
        /// {
        ///    tssStatus.Text = "开始任务...";
        /// }));
        /// CrossThreadCalls.SafeInvoke(this,this.rtxtChat, new CrossThreadCalls.InvokeHandler(delegate()
        /// {
        ///     rtxtChat.AppendText("测试中");
        /// }));
        /// 参考:http://wenku.baidu.com/view/f0b3ac4733687e21af45a9f9.html
        /// <summary>
        public static void SafeInvoke(Control control, InvokeHandler handler)
        {
            if (control.InvokeRequired)
            {            
                control.Invoke(handler);
            }
            else
            {
                handler();
            }
        }