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 に答える