Reputation: 59
I have an app which crashes when trying to open a SaveFileDialog. I searched for answers and I found that I needed to put this in a new thread, and that's what I did but I had an error about the STA. So I put
th.SetApartmentState(ApartmentState.STA);
After few issues, I managed to make the thread work but now I have
Thread was in an invalid state for the operation being executed.
This is my Thread function :
public static void ouvrir(object name)
{
saveFileDialog1.Filter = "Microsoft Word Document (.docx)|*.docx";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.Title = "Where to save the " + (string)name + " ? ";
DialogResult result = saveFileDialog1.ShowDialog();
oke = true;
try
{
if (result == DialogResult.OK)
{
boule = true;
ptth = saveFileDialog1.FileName;
}
}
catch (Exception exc)
{ MessageBox.Show(exc.Message); }
}
This line thows the error (I save a word doc using interop):
doc.SaveAs(imp);
I googled the error but it seems that i'm the only one on earth to have this issue... This is way out of my understanding, I sail in an ocean of doubt and ignorance.
Thank you
Upvotes: 1
Views: 1188
Reputation: 2986
You must show the dialog on the same thread you used to create the form, so you shouldn't use a thread here at all. If you need to invoke the save dialog from a worker thread, use the Invoke method to execute the code on the UI thread.
Example: How to update the GUI from another thread in C#?
Here's some more information from MSDN: Control.InvokeRequired Property
Upvotes: 1