简体   繁体   中英

STA thread for dialog boxes

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());

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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM