0
我試圖在WebClient對象從站點讀取時嘗試獲取進度條以顯示程序正在加載(使用ProgressStyle.Marquee)。問題在於,一旦點擊開始呼叫的按鈕,整個UI就會凍結。我試着把它放在BackgroundWorker doWork中,但是它導致它永遠不會獲取任何數據。我也試過代表和各種線程選項,但似乎都有同樣的問題。在等待WebClient時繼續進行用戶界面
我對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
}
}
發佈您的BackgroundWorker嘗試,這是在Windows窗體中執行後臺工作的正常方法。 – nvoigt 2013-04-29 20:38:25
您是否檢查過您的WebClient實際上終止讀取數據?即「界面凍結」意味着你必須等待一段時間,但遲早你會回到你的應用程序,還是永遠掛掉?在後一種情況下,你必須找出如何表示沒有什麼可以閱讀的內容,然後才能嘗試將操作放入工作線程(最後確實是一個好主意)。 – Matthias 2013-04-29 21:16:12