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

时间:2013-01-18 07:20:09

标签: c# multithreading httpwebrequest backgroundworker windows-phone-8

我的代码出了什么问题?后台工作程序是否未正确设置导致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");
                    });
            }

     }

1 个答案:

答案 0 :(得分:0)

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