【发布时间】:2014-01-20 08:56:54
【问题描述】:
我正在为 Windows 窗体应用程序开发一个插件,用于在地图上显示终端的位置(在 WebBrowser 控件中)。案例如下:
- 用户点击按钮(调用插件);
- 创建异步 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.我知道如何使用 async/await 但不能使用它们 - 我必须使用 .NET 4.0 和 VS2010 - Microsoft.Bcl.Async 无能为力。
【问题讨论】:
标签: c# .net winforms asynchronous