简体   繁体   中英

Access main thread control in backgroundworker thread

I have a function ShowPanel(Control ctrl) which required to pass Control as parameter. I need to call this function in background worker thread. I use following code

void bw_DoWork(object sender,DoWorkEventArgs e)
{                      
    ShowPanel(listBox1);           
}

But fails with execption

Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on

How can I pass listBox1 here in background thread ?

serilize the call , since you can not access a control which is created on different thread , you need to seriliaze the call using below

 void bw_DoWork(object sender,DoWorkEventArgs e)
 {                      
   this.Invoke(new MethodInvoker(delegate {

              ShowPanel(listBox1);           
    })); 
 }

I suppose there should be BeginInvoke instead of Invoke.

Otherwise here's more generic solution.

You need to add a reference to WindowsBase.dll.

On the main thread get thread's dispatcher:

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);}));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM