两个程序同一类型错误程序1:
private void button1_Click(object sender,EventArgs e)
{
Thread aaa=new Thread(new ThreadStart(bbb));
aaa.Start();
}
void bbb()
{
OpenFileDialog openFileDialog=new OpenFileDialog();
openFileDialog.ShowDialog();//此句报错
}
报错:“在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试器附加到该进程才会引发此异常。”
但是我不调试直接运行时,发现在“打开”对话框里面点“我的电脑”里面什么都没有!程序2:
public class Form1:Form
{
public Form1()
{
Button button1=new Button();
button1.Click+=new EventHandler(button1_Click);
this.Controls.Add(button1);
} private void button1_Click(object sender,EventArgs e)
{
Thread aaa=new Thread(new ThreadStart(bbb));
aaa.Start();
}
void bbb()
{
Form2 f=new Form2();
f.ShowDialog();//此句报错
}
}
public lass Form2:Form
{
public Form2()
{
DataGridView dataGridView=new DataGridView();
this.Controls.Add(dataGridView);
DataTable t=new DataTable();
t.Columns.Add();
dataGridView.DataSource=t;
}
}
打开了Form2后按Ctrl+C时报错:“在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。”
private void button1_Click(object sender,EventArgs e)
{
Thread aaa=new Thread(new ThreadStart(bbb));
aaa.Start();
}
void bbb()
{
OpenFileDialog openFileDialog=new OpenFileDialog();
openFileDialog.ShowDialog();//此句报错
}
报错:“在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试器附加到该进程才会引发此异常。”
但是我不调试直接运行时,发现在“打开”对话框里面点“我的电脑”里面什么都没有!程序2:
public class Form1:Form
{
public Form1()
{
Button button1=new Button();
button1.Click+=new EventHandler(button1_Click);
this.Controls.Add(button1);
} private void button1_Click(object sender,EventArgs e)
{
Thread aaa=new Thread(new ThreadStart(bbb));
aaa.Start();
}
void bbb()
{
Form2 f=new Form2();
f.ShowDialog();//此句报错
}
}
public lass Form2:Form
{
public Form2()
{
DataGridView dataGridView=new DataGridView();
this.Controls.Add(dataGridView);
DataTable t=new DataTable();
t.Columns.Add();
dataGridView.DataSource=t;
}
}
打开了Form2后按Ctrl+C时报错:“在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。”
http://blog.csdn.net/knight94/archive/2006/03/16/626584.aspx
http://blog.csdn.net/Knight94/archive/2006/05/27/757351.aspx
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
我知道是在新线程中,也知道会出现问题,我现在想解决问题!
private void button1_Click(object sender,EventArgs e)
{
Thread aaa = new Thread(new ThreadStart(OpenDialogOnOtherThread));
aaa.Start();
}//其它线程打开对话框
void OpenDialogOnOtherThread()
{
MyMethod OpenDialog = new MyMethod(this.OpenDialog);
this.Invoke(OpenDialog); //在当前线程,调用OpenDialog
}//打开对话框
void OpenDialog()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
}