Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WinForms: How to set Main function STAThreadAttribute

Tags:

c#

winforms

I get the following exception when calling saveFileDialog.ShowDialog() in a background thread:

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.

According to this:

To fix the problem, insert the statement:

Threading.Thread.CurrentThread.ApartmentState = Threading.ApartmentState.STA; 

in Main right before the Application.Run statement.

But the Application.Run statement is in Program.cs which seems to be generated code so any changes might be unexpectedly lost. Also, I could not find a way to set current thread to STA in the project or main form properties but maybe I am looking in the wrong place. What is the proper way to call saveFileDialog.ShowDialog() in a background thread?

like image 354
jacknad Avatar asked Jun 16 '11 14:06

jacknad


2 Answers

Solution very easy; Just add this on top of the Main method [STAThread]

So your main method should look like this

 [STAThread]  static void Main(string[] args)  {      ....  } 

It works for me.

like image 142
MILAD Avatar answered Sep 23 '22 00:09

MILAD


ShowDialog() shouldn't be called from a background thread - use Invoke(..).

Invoke((Action)(() => { saveFileDialog.ShowDialog() })); 
like image 32
Nathan Avatar answered Sep 19 '22 00:09

Nathan