【问题标题】:MyThread.Join() blocks the whole application. Why?MyThread.Join() 会阻塞整个应用程序。为什么?
【发布时间】:2009-10-03 19:44:57
【问题描述】:

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

        }
    }

【问题讨论】:

    标签: c# multithreading invoke


    【解决方案1】:

    您在辅助线程中调用 DownloadFiles,但此函数通过 DownloadListView.Invoke 在 UI 线程中调用 Download() -->您的应用程序冻结,因为下载是在主线程中完成的。

    你可以试试这个方法:

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

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2015-04-27
      • 2013-03-19
      • 2017-07-14
      • 2021-10-19
      • 1970-01-01
      相关资源
      最近更新 更多