0

我正在尝试获取一个进度条来显示程序正在加载(使用 ProgressStyle.Marquee),同时 WebClient 对象从站点读取。问题是,在单击开始呼叫的按钮时,整个 UI 会冻结。我尝试将它放在 BackgroundWorker doWork 中,但这会导致它根本无法获取任何数据。我也尝试过委托和各种线程选项,但似乎都有同样的问题。

我对 C# 相当陌生,并且大部分时间都在尝试我在网上找到的结果,但似乎没有一个能解决我的问题。

我有的:

private void getInfoButton_Click(object sender, EventArgs e)
{
    progressBar1.Style = ProgressBarStyle.Marquee;
    getInfoButton.Enabled = false;
    StreamReader reader = new StreamReader(client.OpenRead("URI here"));
    while ((line = reader.ReadLine()) != null) {
        // Do stuff
    }
    progressBar1.Style = ProgressBarStyle.Continuous;
    getInfoButton.Enabled = true;
}

我对 BackgroundWorker 的尝试

private void getInfoButton_Click(object sender, EventArgs e)
{
    progressBar1.Style = ProgressBarStyle.Marquee;
    getInfoButton.Enabled = false;
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWord += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerAsync("URI here");
    while (bw.IsBusy)
        ;
    progressBar1.Style = ProgressBarStyle.Continuous;
    getInfoButton.Enabled = true;
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    WebClient client = new WebClient();
    StreamReader reader = new StreamReader(e.Argument);
    while ((line = reader.ReadLine()) != null) {
        // Do stuff
    }        
}
4

1 回答 1

0

在查看了我的 BackgroundWorker 尝试后,我意识到它正在击败异步点,并且该getInfoButton_Click方法将停止(有效地冻结 UI)直到它完成。再玩一下 BackgroundWorker,我设法让它工作:

private void getInfoButton_Click(object sender, EventArgs e)
{
    progressBar1.Style = ProgressBarStyle.Marquee;
    getInfoButton.Enabled = false;
    BackgroundWorker bw = new BackgroundWorker();
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
    bw.RunWorkerAsync("URI Here");
}

void bw_DoWork(object sender, DoWorkEventArgs e)
{
        WebClient client = new WebClient();
        StreamReader reader = new StreamReader(client.OpenRead(e.Argument));
        e.Result = reader;
}

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    StreamReader reader = (StreamReader)e.Result;
    while ((line = reader.ReadLine()) != null) {
        // Do stuff
    }
    progressBar1.Style = ProgressBarStyle.Continuous;
    getInfoButton.Enabled = true;
}
于 2013-04-30T06:28:29.900 回答