UI冻结1或2秒使用httprequest后台工作器

本文关键字:httprequest 后台 工作 冻结 2秒 UI | 更新日期: 2023-09-27 17:54:20

我的代码有什么问题?是否后台工作器没有正确设置导致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冻结1或2秒使用httprequest后台工作器

我认为你在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)