2

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

     }
4

1 回答 1

0

我认为您对 UI 线程做的工作太多,而在后台线程上做的工作还不够ReadCallback。尝试在传递给的 lambda 函数之外尽可能多地移动 (*) BeginInvoke()

(*) 即在没有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在后台线程中安全使用)

于 2013-01-18T09:43:53.660 回答