MyThread.Join () блокирует все приложение. Зачем? - PullRequest
0 голосов
/ 03 октября 2009

Я хочу скачать файл с FTP-сервера в другом потоке. Проблема в том, что этот поток вызывает зависание моего приложения. Здесь у вас есть код, что я делаю не так? Любая помощь будет благодарна:)

(Конечно, я хочу прекратить зацикливание, пока поток ReadBytesThread не прекратит работу.) Я делаю новую тему:

    DownloadThread = new Thread(new ThreadStart(DownloadFiles));
    DownloadThread.Start();


    private void DownloadFiles()
    {
        if (DownloadListView.InvokeRequired)
        {
            MyDownloadDeleg = new DownloadDelegate(Download);
            DownloadListView.Invoke(MyDownloadDeleg);
        }
    }

    private void Download()
    {
        foreach (DownloadingFile df in DownloadingFileList)
        {
            if (df.Size != "<DIR>") //don't download a directory
            {
                ReadBytesThread = new Thread(() => { 
                                                    FileData = sendPassiveFTPcmd("RETR " + df.Path + "/" + df.Name + "\r\n");
                                                    FileStream fs = new FileStream(@"C:\Downloads\" + df.Name, FileMode.Append);
                                                    fs.Write(FileData, 0, FileData.Length);
                                                    fs.Close();
                                                    });
                ReadBytesThread.Start();
    (here->)    ReadBytesThread.Join();

                MessageBox.Show("Downloaded");
            }

        }
    }

1 Ответ

5 голосов
/ 03 октября 2009

вы вызываете DownloadFiles во вторичном потоке, но этот вызов функции Download() в потоке пользовательского интерфейса через DownloadListView.Invoke -> ваше приложение зависает, потому что загрузка выполняется в основном потоке.

Вы можете попробовать этот подход:

DownloadThread = new Thread(new ThreadStart(DownloadFiles));
DownloadThread.Start();

private void DownloadFiles()
{
    foreach (DownloadingFile df in DownloadingFileList)
    {
        if (df.Size != "<DIR>") //don't download a directory
        {
            ReadBytesThread = new Thread(() => { 
              FileData = sendPassiveFTPcmd("RETR " + df.Path + "/" + df.Name + "\r\n");
              FileStream fs = new FileStream(@"C:\Downloads\" + df.Name, 
                                             FileMode.Append);
              fs.Write(FileData, 0, FileData.Length);
              fs.Close();
                                                });
            ReadBytesThread.Start();
            ReadBytesThread.Join();

            if (DownloadListView.InvokeRequired)
            {
                DownloadListView.Invoke(new MethodInvoker(delegate(){
                    MessageBox.Show("Downloaded");
                }));
            }

        }
    }        
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...