c#在多线程中访问控件

在WPF中
public static class ControlExtention
    {
        
public delegate void InvokeHandler();
        
//同步访问控件
        public static void SafeInvoke(this Control control, InvokeHandler handler)
        {
            
if (control.CheckAccess())
            {
                handler();
            }
            
else
            {
                control.Dispatcher.Invoke(handler);
            }
        }
        
//异步访问控件
        public static void SafeBeginInvoke(this Control control, InvokeHandler handler)
        {
            
if (control.CheckAccess())
            {
                handler();
            }
            
else
            {
                control.Dispatcher.BeginInvoke(handler);
            }
        }
    }

在winform中

public static class ControlExtention
    {
        
public delegate void InvokeHandler();

        
public static void SafeInvoke(this Control control, InvokeHandler handler)
        {
            
if (control.InvokeRequired)
            {
                control.Invoke(handler);
            }
            
else
            {
                handler();
            }
        }
    }
如果直接更改label1里面text内容将引发错误,用下面这个方法就可以实现更改。
Thread thread1 = new Thread(delegate()
            {
                
this.SafeInvoke(() => { label1.Text = "可以更改标题了"; });
            });
            thread1.Start();
posted @ 2009-07-29 12:44  孙鹏  阅读(1370)  评论(1)    收藏  举报