0

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());
tarpista
  • 99
  • 10
  • Mostly UI Components (COM) are not ThreaSafe at all and won't run properly in MTA environments. – codeteq Feb 03 '17 at 16:18
  • When you declare a thread STA you make a promise that you will not block the thread and you will have a message pump running. If you do block a STA thread or do not have a message pump on it random bad things can happen. See [this answer](http://stackoverflow.com/a/4530773/80274) for some more details. – Scott Chamberlain Feb 04 '17 at 21:09
  • 1
    @ScottChamberlain True, but `Thread.Join` *is* a pumping wait. I suspect this would work fine if the caller wasn't a UI thread. – Luaan Feb 14 '17 at 13:10

1 Answers1

1

I could not figure out exactly what makes the calling thread hanging up on the join() when it is waiting for an STA thread to finish, but it looks like that it sometimes works, sometimes does not. Finaly I decided to overcome by using:

while (InvokeResult == DialogResult.None) Application.DoEvents();

instead of the Join().

tarpista
  • 99
  • 10