【发布时间】:2011-02-17 21:43:29
【问题描述】:
我正在尝试制作一个简单的下载器,但我无法更新表单中的 GUI 元素 (Form1)。
在 Form1 的构造函数中,我调用线程:
Thread t = new Thread(new ThreadStart(fetch));
t.Start();
而 fetch 看起来像这样:
private void fetch()
{
try
{
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
webClient.DownloadFile(updateurl, @"foo.iso");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.InnerException.ToString());
}
}
没有任何事件被触发...尽管如此,通过查看文件夹中的 foo.iso,我看到文件的大小增加了。
其中一个事件如下所示:
void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = (int)(e.BytesReceived * 100 / e.TotalBytesToReceive);
statusLabel.Text = "Downloading";
descLabel.Text = progressBar.Value + " % complete";
}
【问题讨论】:
-
一般情况下,不要显式启动线程,使用线程池中的后台线程。使用 QueueUserWorkItem 或其他依赖于池的调用来执行此操作。 stackoverflow.com/questions/684640/…
标签: c#