Update other GUI via BackgroundWorker thread?

C

Carl

Hi,

I know that you should not update the applications GUI with code running in
the BackgroundWorker thread (or any other thread). But is it OK to
construct, show and update new Forms inside the thread? The difference I'm
trying to point out is that you don't update any existing GUI, but instead,
create (of example) a new small form with a progress indicator, OK?

regards

Carl
 
R

Rob

Carl said:
I know that you should not update the applications GUI with code running in
the BackgroundWorker thread (or any other thread). But is it OK to
construct, show and update new Forms inside the thread? The difference I'm
trying to point out is that you don't update any existing GUI, but instead,
create (of example) a new small form with a progress indicator, OK?

Yes and no.

Yes: WinForms GUI objects are bound to the thread they are created on and
can be updated from that thread. It doesn't matter if that thread is the
main UI thread or a secondary thread, so long as the thread is consistent.

No: This can't be done on a BackgroundWorker thread. WinForms UI needs to
be on an STA thread, and BackgroundWorkers are MTA. Any UI thread will have
to pump messages, so the thread will need to call Application.Run or
Form.ShowDialog to activate a message pump.

In general, it's best to keep the UI on the main thread and have the
BackgroundWorker periodically call ReportProgress to let the UI thread know
to update the progress bar.

--Rob
 
C

Carl

Thanks for your great answer!

regards,

Carl

Rob said:
Yes and no.

Yes: WinForms GUI objects are bound to the thread they are created on and
can be updated from that thread. It doesn't matter if that thread is the
main UI thread or a secondary thread, so long as the thread is consistent.

No: This can't be done on a BackgroundWorker thread. WinForms UI needs to
be on an STA thread, and BackgroundWorkers are MTA. Any UI thread will
have
to pump messages, so the thread will need to call Application.Run or
Form.ShowDialog to activate a message pump.

In general, it's best to keep the UI on the main thread and have the
BackgroundWorker periodically call ReportProgress to let the UI thread
know
to update the progress bar.

--Rob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top