C# WinForms: How to set Main function STAThreadAttribute

前端 未结 5 1706
轮回少年
轮回少年 2020-11-27 06:55

I get the following exception when calling saveFileDialog.ShowDialog() in a background thread:

Current thread must be set to single thr

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 07:21

    Add following code on FormLoad

    private void Form1_Load(object sender, EventArgs e)
    {
        Thread myth;
        myth = new Thread(new System.Threading.ThreadStart(CallSaveDialog)); 
        myth.ApartmentState = ApartmentState.STA;
        myth.Start();
    }
    

    Here CallSaveDialog is a thread and here you can call ShowDialog like this

    void CallSaveDialog(){saveFileDialog.ShowDialog();}
    

提交回复
热议问题