Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single thread apartment issue

From my mainform I call the following to open a new form

MyForm sth = new MyForm();
sth.show();

Everything works great however this form has a combobox that, when I switch its AutoCompleteMode to suggest and append, I got this exception while showing the form:

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.

I have set this attribute on my main function as requested by the exception:

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

Can I please get some help as to understand what might be wrong.

Sample code:

private void mainFormButtonCLick (object sender, EventArgs e)
{
    // System.Threading.Thread.CurrentThread.SetApartmentState(ApartmentState.STA); ?
    MyForm form = new MyForm();
    form.show();
}

Designer:

this.myCombo.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.myCombo.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.myCombo.FormattingEnabled = true;
this.myCombo.Location = new System.Drawing.Point(20, 12);
this.myCombo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
this.myCombo.Name = "myCombo";
this.myCombo.Size = new System.Drawing.Size(430, 28);
this.myCombo.Sorted = true;
this.myCombo.TabIndex = 0; phrase";

Setting data source

public MyForm(List<string> elem)
{
    InitializeComponent();
    populateColorsComboBox();
    PopulateComboBox(elem);
}

public void PopulateComboBox(List<string> list )
{
    this.myCombo.DataSource = null;
    this.myCombo.DisplayMember = "text";
    this.myCombo.DataSource = list;
}
like image 546
santBart Avatar asked Nov 27 '12 08:11

santBart


Video Answer


2 Answers

Is Main(string[] args) really your entry point?

Maybe you have another Main() overload with no parameters. Or some other Main() in another class. Please open Project properties and look for the start object.

like image 138
Jürgen Steinblock Avatar answered Oct 15 '22 06:10

Jürgen Steinblock


Windows Forms applications must be run in the STA method.

See here: Could you explain STA and MTA?

And COM comes into play since windows forms comes into play since the controls themselves use native windows handles and thus must adhere to the STA model. I do believe that the reason you get the error at this specific place is that a second thread is created/ used internally by the AutoCompletion.

And as far as I have expereienced, the threading model must be set in Main, changing it later only works from STA to MTA, but not the other way round

like image 27
Mario The Spoon Avatar answered Oct 15 '22 06:10

Mario The Spoon