C# WinForms: How to set Main function STAThreadAttribute

前端 未结 5 1568
轮回少年
轮回少年 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();
     });
    
    0 讨论(0)
  • 2020-11-27 07:09

    Solution very easy; Just add this on top of the Main method [STAThread]

    So your main method should look like this

     [STAThread]
     static void Main(string[] args)
     {
         ....
     }
    

    It works for me.

    0 讨论(0)
  • 2020-11-27 07:14

    this should work if you are creating the thread in which you call the showDialog:

    var thread = new Thread(new ParameterizedThreadStart(param => { saveFileDialog.ShowDialog(); }));
     thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    
    0 讨论(0)
  • 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();}
    
    0 讨论(0)
  • 2020-11-27 07:22

    ShowDialog() shouldn't be called from a background thread - use Invoke(..).

    Invoke((Action)(() => { saveFileDialog.ShowDialog() }));
    
    0 讨论(0)
提交回复
热议问题