views:

136

answers:

1

Hi, I want to download a file from a FTP server in the other Thread. The problem is, this thread causes that my application is freezed. Here You have the code, what am I doing wrong? Any help will by grateful :)

(Of course I want to stop looping until the thread 'ReadBytesThread' terminates.) I make a new thread:

    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");
            }

        }
    }
+5  A: 

you're calling DownloadFiles in a secondary thread but this function call Download() in the UI thread via DownloadListView.Invoke --> your application freezes because the download is done in the main thread.

you can try this approach:

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");
                }));
            }

        }
    }        
}
najmeddine