0

嗨 ppl 我试图在我用 C# 下载文件时让它写下载我尝试了线程方法但它在下载完成后仍然在写代码如下;

  public void yap(object o)
    {

      (o as Label).Text ="DOWNLOADING";

    }

    private void button1_Click(object sender, EventArgs e)
    {
        CheckForIllegalCrossThreadCalls = false;
        ParameterizedThreadStart p = new ParameterizedThreadStart(yap);
        Thread t = new Thread(p);
        t.Start(label2);
        string yol = Environment.CurrentDirectory;
        FtpWebRequest FTP;
        try
        {

            FileStream SR = new FileStream(yol + "\\list.gz", FileMode.Create);

            FTP = (FtpWebRequest)FtpWebRequest.Create
  (new  Uri("ftp://"+textBox1.Text+"/" + "/usr/valapp/etc/list.gz"));

            FTP.Credentials = new NetworkCredential("username", "password");

            FTP.Method = WebRequestMethods.Ftp.DownloadFile;

            FTP.UseBinary = true;

            FtpWebResponse response = (FtpWebResponse)FTP.GetResponse();

            Stream ftpStream = response.GetResponseStream();

            long cl = response.ContentLength;

            int bufferSize = 2048;
            int readCount;

            byte[] buffer = new byte[bufferSize];
            readCount = ftpStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                SR.Write(buffer, 0, readCount);
                readCount = ftpStream.Read(buffer, 0, bufferSize);
            }
            ftpStream.Close();
            SR.Close();
            response.Close();
            MessageBox.Show("File Downloaded!");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "ERROR");
        }
    }

}
}  

正如我所说的代码正在工作,但我只想同时写下载或首先谢谢你。

4

1 回答 1

0

对于 windows 应用程序,我认为最好的方法是使用BackgroundWorkerDispatcher.Invoke()更新标签的文本。

private void button1_Click(object sender, EventArgs e)
{
      //Update label text here..

      BackgroundWorker _backgroundWorker = new BackgroundWorker();
      _backgroundWorker.DoWork += _backgroundWorker_DoWork;
      _backgroundWorker.RunWorkerAsync();
}

void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
        Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background,
            new Action(delegate()
        {
            //Download code here..
        }));
}
于 2013-07-18T07:10:39.907 回答