Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing code execution on main thread

How can I force a section of code to be executed on my main thread?

This is why I'd like to know:

I have a custom created message box that at times gets shown from a thread that is not the main thread. However, when the message box constructor is called I get an InvalidOperationException saying "The calling thread must be STA, because many UI components require this." This makes sense, UI elements need to be handled on the main thread.

My MessageBox.ShowMessage(...) function is a static function that creates an instance of my custom message box and shows it. Is there a something I could put in ShowMessage that would force the message box to be created and shown on the main thread? Elsewhere in my code I use the Control.BeginInvoke to handle similar issues, but since it is a static function there is no already existing UI element for me to call BeginInvoke on.

Do I have to call MessageBox.ShowMessage from with a Control.BeginInvoke? I'd prefer the BeginInvoke (or some equivalent) to be called from within ShowMessage.

like image 720
Dan Vogel Avatar asked Apr 24 '09 21:04

Dan Vogel


1 Answers

There are a few options here:

  • make the second thread STA (you can only do this for your own Thread - not for ThreadPool threads) - via .SetApartmentState(ApartmentState.STA);
  • see if SynchronizationContext.Current is non-null; if so, use Send/Post
  • pass the form/control in as an ISynchronizeInvoke instance (may not apply to WPF - I'm not 100% sure)
like image 94
Marc Gravell Avatar answered Sep 22 '22 00:09

Marc Gravell