[英]UI freezes for 1 or 2 sec using httprequest background worker
我的代碼有什么問題? 后台工作程序是否未正確設置,導致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");
});
}
}
我認為您對UI線程做了太多工作,而在后台線程上ReadCallback
卻做得不夠。 嘗試在傳遞給BeginInvoke()
的lambda函數之外盡可能多地(*)移動。
(*),即安全無InvalidCrossThreadExceptions
或競爭條件...
在這種情況下,請嘗試以下操作:
string resultString = streamReader1.ReadToEnd();
JsonMainProgressbar progressBarValue;
progressBarValue = JsonConvert.DeserializeObject<JsonMainProgressbar>(resultString);
int progressBarValueInt = Convert.ToInt32(progressBarValue.userclicks /
progressBarValue.countryclicks * 100);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.ProgressBar.Value = progressBarValueInt;
this.txtContribution.Text = "your contribution: " + progressBarValueInt + "%";
Debug.WriteLine("Progressbar updated");
});
(假設您可以在后台線程中安全地使用JsonMainProgressBar
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.