gpt4 book ai didi

c# - 使用 httprequest background worker UI 卡住 1 或 2 秒

转载 作者:太空宇宙 更新时间:2023-11-03 16:19:53 24 4
gpt4 key购买 nike

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

关于c# - 使用 httprequest background worker UI 卡住 1 或 2 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14394177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com