繁体   English   中英

对话框的STA线程

[英]STA thread for dialog boxes

要在Windows窗体应用程序中使用对话框,要么将主线程设置为[STAThread]要么需要创建一个单独的STA线程来运行对话框。

这是我无法真正理解的问题。 启动的STA线程“有时”没有完成,因此主线程一直挂在Join()上。

现在,我通过使用Application.DoEvents()而不是t.Join()克服了问题,现在看来工作正常,但是我仍然会对“有时”的含义感兴趣。 在示例中,我使用以下静态方法打开一个openfile- / savefile对话框:

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;
        }
    }
}

因此用法仅仅是:

Dialog.clsShowDialog.STAShowDialog(new SaveFileDialog());

我无法弄清楚到底是什么导致调用线程在等待STA线程完成时挂在join()上,但是看起来有时它可以工作,有时却不能。 最后,我决定使用以下方法来克服:

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

而不是Join()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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