To use dialog boxes in windows form applications either the main thread should be set as [STAThread]
or a separate STA thread needs to be created for the dialog box to run on.
Here comes the issue I could not realy understand. A started STA thread does not finish "sometimes", so the main thread keeps hanging up on the Join().
Now I overcome by using Application.DoEvents()
instead of the t.Join()
and now it seems working fine, but I would be still interested in what "sometimes" is depending on. In example I use the following static method to open up an openfile-/savefile dialog:
using System.Windows.Forms;
namespace Dialog
{
public class clsDialogState
{
public DialogResult result;
public FileDialog dialog;
public void ThreadProcShowDialog()
{
result = DialogResult.None;
result = dialog.ShowDialog();
}
}
public static class clsShowDialog
{
public static DialogResult STAShowDialog(FileDialog dialog)
{
clsDialogState state = new clsDialogState();
state.dialog = dialog;
System.Threading.Thread t = new System.Threading.Thread(state.ThreadProcShowDialog);
t.SetApartmentState(System.Threading.ApartmentState.STA);
t.Start();
//t.Join(); //Main thread might hang up here
while (state.result == DialogResult.None) Application.DoEvents(); //Everything is refreshed/repainted fine
return state.result;
}
}
}
So usage is simply just:
Dialog.clsShowDialog.STAShowDialog(new SaveFileDialog());