c#在多线程中访问控件
在WPF中
在winform中
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);
}
}
}
{
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内容将引发错误,用下面这个方法就可以实现更改。{
public delegate void InvokeHandler();
public static void SafeInvoke(this Control control, InvokeHandler handler)
{
if (control.InvokeRequired)
{
control.Invoke(handler);
}
else
{
handler();
}
}
}
Thread thread1 = new Thread(delegate()
{
this.SafeInvoke(() => { label1.Text = "可以更改标题了"; });
});
thread1.Start();
{
this.SafeInvoke(() => { label1.Text = "可以更改标题了"; });
});
thread1.Start();

浙公网安备 33010602011771号