我的代码有什么问题?后台工作人员是否未正确设置导致 UI 冻结?似乎延迟在调用 BeginGetResponse 时开始,然后在从 Web 服务器返回结果后正常恢复。
private void updateProgressbar()
{
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerAsync();
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
string path = "http://www.somestring.com/script.php?a=b");
Uri uriString = new Uri(path);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriString);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)";
request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
}
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
using (StreamReader streamReader1 = new StreamReader(response.GetResponseStream()))
{
string resultString = streamReader1.ReadToEnd();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
JsonMainProgressbar progressBarValue;
progressBarValue = JsonConvert.DeserializeObject<JsonMainProgressbar>(resultString);
this.ProgressBar.Value = Convert.ToInt32(progressBarValue.userclicks / progressBarValue.countryclicks * 100);
this.txtContribution.Text = "your contribution: " + this.ProgressBar.Value + "%";
Debug.WriteLine("Progressbar updated");
});
}
}