0

我想从另一个线程中的 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");
            }

        }
    }
4

1 回答 1

5

您正在DownloadFiles辅助线程中调用,但此函数调用Download()在 UI 线程中通过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");
                }));
            }

        }
    }        
}
于 2009-10-03T19:47:35.713 回答