1

我遇到了一些线程问题,我需要从文件夹浏览器对话框中获取路径这是一个代码

Thread t = new Thread(() => myFolderBrowserDialog.ShowDialog());
                    t.IsBackground = true;
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
4

2 回答 2

9

你可以这样做:

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
    }
}
于 2012-10-29T16:53:41.023 回答
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 中获取路径:

    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 位中对我有用。在调试器中以及当我在客户端机器上执行程序时。

于 2012-10-29T17:41:16.447 回答