Ton*_*ony 0 c# multithreading invoke
我想从另一个线程中的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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
你正在调用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");
}));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)