C# WinForms: How to set Main function STAThreadAttribute

前端 未结 5 1701
轮回少年
轮回少年 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:01

    On your MainForm:

    if (this.InvokeRequired) { 
     this.Invoke(saveFileDialog.ShowDialog()); 
    } else { 
     saveFileDialog.ShowDialog(); 
    }
    

    Or, if you will have other methods that need to be run from the UI thread:

      private void DoOnUIThread(MethodInvoker d) {
         if (this.InvokeRequired) { this.Invoke(d); } else { d(); }
      }
    

    Then, call your method as such:

     DoOnUIThread(delegate() {
        saveFileDialog.ShowDialog();
     });
    

提交回复
热议问题