3

I have a ThreadStateException that i need to have STAThread... The problem appeared yesterday, I even ckecked previous versions from my git repo (which were 100% working) - now they're not.

Code for main:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new ClientList());
}

And ClientList form method:

private void button2_Click(object sender, EventArgs e)
{
    [...]
    OpenFileDialog ofd = new OpenFileDialog();
    DialogResult result = ofd.ShowDialog();
    [...]
}

Any idea why STA won't work?

EDIT: In new (test) application everything works fine. Only this project throws an exception on OpenFileDialog.

EDIT 2: The getAppartmentState shows that app is in MTA from the very first line of Main. Is [STAThread] ignored?

Ibrahim Amer
  • 1,147
  • 4
  • 19
  • 46
kaczmen
  • 528
  • 4
  • 12
  • May help: [A ThreadStateException occures when trying to restart a thread](http://stackoverflow.com/q/13170/471214) – mmdemirbas Jul 19 '12 at 12:05
  • Fine, but I'm not creating my own Thread. It's main entry of the app and I personally don't know other way to set its apartment than [STAThread] – kaczmen Jul 19 '12 at 12:16
  • 1
    Verify or log `System.Threading.Thread.CurrentThread.ApartmentState` at the start of the click handler. – H H Jul 19 '12 at 12:24
  • According to "[ThreadStateException Error in openfiledialog](http://social.msdn.microsoft.com/forums/en-US/winforms/thread/180fde7b-ee75-4a6e-bb8e-c56b1552415d/)", adding `thread.SetApartmentState (ApartmentState.STA);` before `OpenFileDalog()` solves. – mmdemirbas Jul 19 '12 at 12:26
  • @HenkHolterman It's MTA of course. – kaczmen Jul 19 '12 at 12:37
  • @mmdemirbas I can't setApartmentState on a running Thread. – kaczmen Jul 19 '12 at 12:38
  • OK, now try to intercapt it ASAP, ie in Main() and/or in Form_Loadded. – H H Jul 19 '12 at 12:41
  • @HenkHolterman It's MTA right from the very first line of Main. Looks like [STAThread] is ignored. – kaczmen Jul 19 '12 at 12:46
  • Good to know. Even better to state so in the question. Comments don't count. – H H Jul 19 '12 at 12:47
  • @HenkHolterman Any idea why it happens? – kaczmen Jul 19 '12 at 13:45
  • Possible duplicate of [STAThread missing, but it is there](https://stackoverflow.com/questions/3584434/stathread-missing-but-it-is-there) – Impurity Aug 21 '18 at 15:53

0 Answers0