我正在尝试获取一个进度条来显示程序正在加载(使用 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
}
}