Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everyone!

I am getting another strange error that I'm hoping I could get some assistance on. The error is a ThreadStateException error.

System.Threading.ThreadStateException was unhandled by user code
Message=Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it.

What I'm trying to do is let a background worker complete and load the new form after hiding the original one. It gets halfway down the designer generated code before this error appears. Below is some context of where the error appears.

C#
this.transmissionCodeComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            this.transmissionCodeComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
            this.transmissionCodeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.transmissionCodeComboBox.Enabled = false;
            this.transmissionCodeComboBox.FormattingEnabled = true;
            this.transmissionCodeComboBox.Location = new System.Drawing.Point(271, 309);
            this.transmissionCodeComboBox.Name = "transmissionCodeComboBox";
            this.transmissionCodeComboBox.Size = new System.Drawing.Size(121, 21);
            this.transmissionCodeComboBox.TabIndex = 65;
            this.transmissionCodeComboBox.SelectedIndexChanged += new System.EventHandler(this.transmissionCodeComboBox_SelectedIndexChanged);


It is failing on this line.
this.transmissionCodeComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;

Does anyone know how this issue can be resolved?

Thanks everyone!
Posted

1 solution

This is quite a usual situation, but you can control your thread apartment state. It actually are done in different ways. You use this attribute when you need to setup you main (entry-point) thread. For all other threads, you can set it in other thread, before your thread is started.

You will find the detail you need in my past answers:
The calling thread must be STA, because many UI components require this while navigation in wpf[^],
Exception System.Threading.ThreadStateEx C#..[^],
example when setting apartment state can be needed: Voice Recognition System[^],
Threading And MTA STA[^],
WPF Application Exception: The calling thread cannot access this object because a different thread owns it[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900