C # Хочу, чтобы OpenFileDialog в STAThread действовал так же без многопоточности - PullRequest
0 голосов
/ 08 ноября 2018

В программе STAThread с обычным OpenFileDialog, если вы щелкнете по родительскому окну, OpenFileDialog мигнет и издаст шум.

В моем приложении у меня есть MTAThread на главной. Поэтому я подумал, что я делаю поток STA, чтобы добиться того же. Проблема, однако, в том, что он перестает вести себя, как раньше. Он просто сидит в ожидании соединения. Обратите внимание на простой пример кода ниже:

private void func()
{
    var fileContent = string.Empty;
    var filePath = string.Empty;

    using (OpenFileDialog openFileDialog = new OpenFileDialog())
    {
        openFileDialog.InitialDirectory = "c:\\";
        openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 2;
        openFileDialog.RestoreDirectory = true;

        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            //Get the path of specified file
            filePath = openFileDialog.FileName;

            //Read the contents of the file into a stream
            var fileStream = openFileDialog.OpenFile();

            using (StreamReader reader = new StreamReader(fileStream))
            {
                fileContent = reader.ReadToEnd();
            }
        }
    }
}

private void button1_Click(object sender, EventArgs e)
{
    //Thread way
    //Thread aThread = new Thread(new ThreadStart(func));
    //aThread.SetApartmentState(ApartmentState.STA);
    //aThread.Start();
    //aThread.Join();

    //Normal way
    func();
}

Могу ли я заставить родительское окно немного подождать, как действовать раньше?

...