【发布时间】:2011-10-15 03:59:48
【问题描述】:
尝试使用 FolderBrowserDialog 时出现以下异常:
System.Threading.ThreadStateException: 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. This exception is only raised if a debugger is attached to the process.
我已经广泛搜索了这个问题,每个人建议的解决方案似乎是将[STAThreadAttribute] 放在 Main 方法之上,从 Debug 文件夹中删除所有 dll,或者使用 Invoke 方法。我已经尝试了所有这些,但仍然遇到同样的异常。
代码如下:
public partial class Form1 : Form
{
public event EventHandler ChooseLocationHandler = null;
public string DestFolder
{
set { textBox1.Text = value; }
get { return textBox1.Text; }
}
public Form1()
{
InitializeComponent();
}
private void ChooseLocationButton_Click(object sender, EventArgs e)
{
if (ChooseLocationHandler != null)
ChooseLocationHandler(this, e);
}
}
在我的演示者中是以下内容:
public partial class Presenter
{
Form1 myForm;
public Presenter()
{
myForm = new Form1();
myForm.ChooseLocationHandler += ChooseLocationHandler;
myForm.Show();
}
public void ChooseLocationHandler(object obj, EventArgs e)
{
Form1 sender = (Form1)obj;
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
fbd.ShowNewFolderButton = true;
if (fbd.ShowDialog() == DialogResult.Cancel)
return;
sender.DestFolder = fbd.SelectedPath;
}
}
我在 fbd.ShowDialog() 上遇到异常。
【问题讨论】:
标签: c# multithreading exception folderbrowserdialog