BackgroundWorker with Webclient downloadstring

时间:2013-05-23 19:13:38

标签: c# backgroundworker webclient downloadstring

所以基本上我想在互联网上检索.txt文件的内容并将其写入标签。但是,虽然它会使Windows窗体冻结。

所以我想把它放到BackgroundWorker中。还有一个进度条,应该在进度中填写。我的代码如下所示:

private void RetrieveTxt(string currentversion)
    {
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    }

void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        WebClient wc = new WebClient();
        label1.Text = wc.DownloadString("http://example.org/version.txt");
    }

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        updateProgress.Value = e.ProgressPercentage;
    }

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        updateProgress.Visible = false;
    }

然而,它不起作用;标签永远不会更新,进度条保持空白。

感谢任何帮助,谢谢! :)

2 个答案:

答案 0 :(得分:4)

如果您使用的是C#5.0,则可以执行以下操作:

label1.Text = await client.DownloadStringTaskAsync("http://example.org/version.txt");

就这么简单。

如果不是,那么您可以利用WebClient的异步支持;您不需要使用BackgroundWorker:

WebClient client = new WebClient();
client.DownloadStringCompleted += (s, data) =>
{
    label1.Invoke(new Action(() => label1.Text = data.Result));
};
client.DownloadStringAsync(new Uri("http://example.org/version.txt"));

至于为什么你的代码不起作用:

  1. 你从未真正开始工作。你从未打电话给worker.RunWorkerAsync();
  2. 您正在从后台任务访问UI控件,因此当您尝试从DoWork处理程序访问标签时它将会中断。您需要将结果设置为WebClient返回的字符串,然后在已完成的处理程序中设置标签。

答案 1 :(得分:1)

您需要委托,因为后台线程无法在UI控件上运行:

private delegate void InvokeUpdateText(String theText);
private void UpdateText(String theText)
{
    if (InvokeRequired)
    {
        try { Invoke(new InvokeUpdateText(UpdateText), theText); }
        catch { }
        return;
    }
    label1.Text = theText;
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    WebClient wc = new WebClient();
    UpdateText("http://example.org/version.txt");
}