簡體   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