我遇到线程问题,我需要从文件夹浏览器对话框获取路径 这是一个代码
Thread t = new Thread(() => myFolderBrowserDialog.ShowDialog());
t.IsBackground = true;
t.SetApartmentState(ApartmentState.STA);
t.Start();
答案 0 :(得分:8)
你可以这样做:
Thread t = new Thread(() => myFolderBrowserDialog.ShowDialog());
t.IsBackground = true;
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
var path = myFolderBrowserDialog.SelectedPath;
但线程中确实存在零点,它与此相同:
myFolderBrowserDialog.ShowDialog(); //this will block until the user presses OK or cancel.
var path = myFolderBrowserDialog.SelectedPath;
就个人而言,我会这样做:
Using (var dialog = new FolderBrowserDialog())
{
//setup here
if (dialog.ShowDialog() == DialogResult.Ok) //check for OK...they might press cancel, so don't do anything if they did.
{
var path = dialog.SelectedPath;
//do something with path
}
}
答案 1 :(得分:1)
我遇到过这样的问题。主线程的apartmentState是[MTAThread]。
在课程开始时我把这些代码:
public class FormWithMTA{
delegate void ModifyTextBox(string value);
private FolderBrowserDialog opn;
Thread runningThread;
...
如果我把这个:
...
opn = new FolderBrowserDialog();
runningThread = new Thread(new ThreadStart(OpenDlg));
//Change the apartmentState of that thread to work in STA if your main ApartmentState are MTA
runningThread.SetApartmentState(ApartmentState.STA);
runningThread.Start();
...
并在runningThread中使用该部分代码获取de path:
private void OpenDlg()
{
opn.Description = "Escolha de diretório:";
opn.ShowNewFolderButton = false;
opn.RootFolder = System.Environment.SpecialFolder.MyComputer;
try
{
DialogResult d = opn.ShowDialog();
if (d == DialogResult.OK)
{
if (opn.SelectedPath != "")
UpdateStatus(opn.SelectedPath);
}
}
catch (InvalidCastException erro)
{
//When work in main with MTA everytime i get that exception with dialog result
if (opn.SelectedPath != "")
UpdateStatus(opn.SelectedPath);
}
catch (Exception er)
{
}
opn.Dispose();
opn = null;
runningThread.Join();
}
void UpdateStatus(string value)
{
if (txtBox.InvokeRequired)
{
//Call the delegate for this component.
txtBox.Invoke(new ModifyTextBox(UpdateStatus), new object[] { value });
return;
}
txtBox.Text = value;
}
嗯,该代码适用于Windows 7 64位。在调试器中以及在客户端计算机上执行程序时。