单线程公寓问题

8
从我的主窗体调用以下代码以打开一个新窗体:
MyForm sth = new MyForm();
sth.show();

一切工作都很顺利,但是这个表单有一个组合框,当我将其AutoCompleteMode设置为suggest和append时,在显示表单时出现了以下异常:

在进行OLE调用之前,当前线程必须设置为单线程公寓 (STA) 模式。确保您的Main函数上已经标记了STAThreadAttribute。

我按照异常提示要求,在我的主函数上设置了此属性:

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

我可以帮忙理解可能出了什么问题。以下是样例代码:

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

设计师:

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";

设置数据源

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;
}

你是如何展示表单的?在主线程中还是在一个独立的线程中? - Alvin Wong
我没有使用任何BackgroundWorker,只是在同一个线程上创建所有东西,就像MainForm一样。 - santBart
你能否发布一些示例代码,以便我也可以尝试一下? - Pratik
这种错误通常发生在主线程在多线程公寓(MTA)下工作时。我不清楚 - 在您添加[STAThread]属性后是否仍会出现错误,或者您想知道为什么需要[STAThread]属性才能纠正错误? - nikita
2
如果在调用 form.Show() 之前添加 if (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA) MessageBox.Show("Not STA");,它会显示消息框吗? - T. Fabre
显示剩余9条评论
3个回答

3

Main(string[] args)是你的入口点吗?

也许你有另一个没有参数的Main()重载函数。或者在另一个类中有其他的Main()函数。请打开项目属性,查找启动对象。


2

Windows Forms应用程序必须在STA方法中运行。

请参见此处:能否解释STA和MTA?

由于控件本身使用本地窗口句柄,因此必须遵守STA模型,因此COM也发挥作用。我确信你在这个特定位置收到错误的原因是AutoCompletion内部创建或使用了第二个线程。

就我所经历的而言,线程模型必须在Main中设置,稍后更改只能从STA到MTA,而不能反过来。


1
作为一个奇思妙想:在第二个表单中创建源列表的深层副本,并将组合框绑定到该列表的副本而不是原始列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接