[英]Access main thread control in backgroundworker thread
我有一个函数ShowPanel(Control ctrl)
,需要将Control
作为参数传递。 我需要在后台工作线程中调用此函数。 我使用以下代码
void bw_DoWork(object sender,DoWorkEventArgs e)
{
ShowPanel(listBox1);
}
但是执行失败
跨线程操作无效:控件“ Form1”从其上创建线程之外的线程访问
如何在后台线程中在此处传递listBox1
?
对调用进行序列化,因为您无法访问在其他线程上创建的控件,因此需要使用以下方法对调用进行序列化
void bw_DoWork(object sender,DoWorkEventArgs e)
{
this.Invoke(new MethodInvoker(delegate {
ShowPanel(listBox1);
}));
}
我想应该有BeginInvoke而不是Invoke。
否则,这里是更通用的解决方案。
您需要添加对WindowsBase.dll的引用。
在主线程上获取线程的调度程序:
public class SomeClass
{
System.Windows.Threading.Dispatcher mainThreadDispatcher;
// assuming class is instantiated in a main thread, otherwise get a dispatcher to the
// main thread
public SomeClass()
{
Dispatcher mainThreadDispatcher = Dispatcher.CurrentDispatcher;
}
public void MethodCalledFromBackgroundThread()
{
mainThreadDispatcher.BeginInvoke((Action)({() => ShowPanel(listBox1);}));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.