我想从另一个Thread中的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");
}
}
}
答案 0 :(得分:5)
您正在辅助线程中调用DownloadFiles
,但此函数通过Download()
- &gt;在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");
}));
}
}
}
}