[英]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.