我正在開發一個插入到Windows窗體應用的插件,用於在地圖上顯示終端的位置(在WebBrowser控件中)。情況如下:等待異步HTTP請求的響應,無異步/等待
- 用戶單擊按鈕(調用插件);
- 異步HTTP請求被創建(確定終端的座標);
- 由於全部收到響應 - 地圖應顯示給用戶。
我寫的代碼:
foreach (var terminal in terminals)
{
var webRequest = (HttpWebRequest)WebRequest.Create(GeoCoder.GeoCodeUrl + terminal.Address);
var taskResp = Task.Factory.FromAsync<WebResponse>(webRequest.BeginGetResponse,
webRequest.EndGetResponse,
terminal.Id);
var taskResult = taskResp.ContinueWith(task =>
{
// Parse the response
});
runningTasks.Add(taskResult);
}
Task.WaitAll(runningTasks.ToArray()); // UI Thread blocks here!
webBrowser1.DocumentText = ...
它會阻止UI線程,因爲我不得不等待,直到我得到所有響應(座標)之前,我可以顯示地圖。我想知道如何避免這種情況(沒有發出同步http請求)?
P.S.我知道如何使用異步/等待,但不能使用它們 - 我必須使用.NET 4.0和VS2010 - Microsoft.Bcl.Async不能幫助)。
我需要調用'webBrowser1.DocumentText = ...',只要我得到**最後一個響應**。我不明白如何使用'ThreadPool.QueueUserWorkItem'來完成它,請給我更多的細節? – Zharro