0

I have a perfectly working application, except in ONE computer. In this computer the application crashes when a SaveFileDialog opens. No errors, no exceptions.

After some research I found that one way to fix this crash is to make this SaveFileDialog in a new thread.

static void open(object name)
{
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.Filter = "Microsoft Word Document (.docx)|*.docx";
    saveFileDialog1.FilterIndex = 2;
    saveFileDialog1.RestoreDirectory = true;
    saveFileDialog1.Title = "Where to save the " + (string)name + " ? ";
    try
    {
        th.IsBackground = false;    
        boule = saveFileDialog1.ShowDialog() == DialogResult.OK;
        ptth = saveFileDialog1.FileName;             
    }
    catch (Exception exc)
    { MessageBox.Show(exc.Message); }
}

I put this in the Event:

Thread th = new Thread(new ParameterizedThreadStart(open));
th.Start("Quotation");

The problem is that I have an error

Current thread must be set to single thread apartment (STA) mode before OLE...

So I checked and I do have the "[STAThread]" before my Main. So I added this line in the "open" method:

th.SetApartmentState(ApartmentState.STA);

But a new error appear :

Failed to set the specified COM apartment state

What did I do wrong ? How to make a proper UI thread ? Is there an easier way?

EDIT : It's even more weird because in the app I use an OpenFileDialog to get a picture and it works perfectly. Is it an issue only for SaveFileDialog? Does it come from something else?

  • I saw the answer recommending a new thread, and it looks questionable. A dialog box *should* be on the UI thread. If something doesn't work for an unknown reason, running it on a new thread is very unlikely to solve anything but could introduce new issues. – Scott Hannen Apr 25 '16 at 01:32
  • Yes I'm not sure too but the fact is that the app crashes and I have to fix it... So maybe someone know another way to make it work, or can explain me how to make a proper thread. – UnderPaidIntern Apr 25 '16 at 01:40
  • Does the savefiledialog crash happen on any app? [This](http://superuser.com/questions/985618/save-file-dialog-viewing-libraries-crash-any-all-desktop-applications) question mentioned libraries as the culprit, which can be avoided by setting your InitialDirectory. – Martheen Apr 25 '16 at 02:41
  • Did you call SetApartmentState() BEFORE thread.Start() ? See http://stackoverflow.com/questions/6917134/failed-to-set-the-specified-com-apartment-state for more details – alexm Apr 25 '16 at 04:04

1 Answers1

0

Instead of starting a new thread you can set the ApartmentState for the current UI thread.

var thread = new Func<Thread>(() => { return Thread.CurrentThread; }).Invoke();
thread.SetApartmentState(ApartmentState.STA);
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62