OpenFileDialog needs STAThread, but I need MTAThread

  • Thread starter Thread starter Shannon Cayze
  • Start date Start date
S

Shannon Cayze

Hello all,

In my Windows Forms app I'm opening an OpenFileDialog. This throws the
following exception because I have the MTAThread attribute on the Main
method:

"Current thread must be set to single thread apartment (STA) mode
before OLE calls can be made. Ensure that your Main function has
STAThreadAttribute marked on it. This exception is only raised if a
debugger is attached to the process."

I can't just change it to STAThread because elsewhere in the same form
I'm using the WaitHandle.WaitAll method as follows, which requires the
MTA apartment state:

// Loop while the thread has not finished
while( this.workerThread.IsAlive )
{
// Wait until the thread indicates that it has stopped.
// Only block for 100 ms so that the UI can remain responsive.
if( WaitHandle.WaitAll( stoppedEvents, 100, true ) )
break;

// Allow any events to process that occurred in
// the UI while waiting
Application.DoEvents();
}

Using the Thread.CurrentThread.SetApartmentState method when necessary
throws the following exception:

"Failed to set the specified COM apartment state."

Can anyone help me understand what I need to do so that both features
work correctly?

Thanks in advance,
Shannon
 
Windows Forms applications simply don't support the MTAThread attribute on
the entry point. There's many other things an WinForms application can use
other than the OpenFileDialogs like the other common dialogs, drag-drop, etc.
that will not be supported.

To support waiting for more than one handle you'll have to spawn another
thread (or use a BackgroundWorker object) to make the call the WaitAll.

It's not a good idea to be calling WaitAll on a GUI thread anyway; that
means you're halting your message pump and your GUI will be non-responsive.
 
Thank you Peter. I haven't had any performance problems, but I didn't
know there was that potential with the technique I was using because I
don't have much experience with thread synchronization. Thank you for
helping me understand a little bit more about the threading best
practices.

Shannon
 
Back
Top