等待响应异步HTTP请求,而不异步/等待 [英] Waiting for responses to asynchronous HTTP requests without async/await

查看:343
本文介绍了等待响应异步HTTP请求,而不异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个插件,Windows窗体应用程序,diplays在地图上终端的位置(在WebBrowser控件)。此案以下内容:

I'm developing a plugin to Windows Forms app that diplays locations of terminals on the map (in WebBrowser control). The case is following:

  1. 在用户点击该按钮(调用插件);
  2. 在异步HTTP请求中创建(确定终端的坐标);
  3. 所有的答复:收到 - 地图应该是diplayed用户
  1. User clicks the button (calls the plugin);
  2. Async HTTP requests are created (determination of coordinates of terminals);
  3. As all the responses are recieved - the map should be diplayed to user.

我写了code:

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请求)?

It blocks UI thread as I have to wait until I get all the responses (coordinates) before I can display the map. I want to know how I can avoid that (without making a synchronous http requests)?

PS 我知道如何与异步做/等待,但不能使用它们 - 我必须使用.NET 4.0和VS2010 - Microsoft.Bcl.Async不能帮助)

P.S. I know how to do it with async/await but cannot use them - I have to use .NET 4.0 and VS2010 - Microsoft.Bcl.Async cannot help).

推荐答案

据我可以看到你打它是如何做到这一点在C#4.0。

As far as I can see you are struck with it how to do it in c# 4.0.

这并不难,要用来做这类工作的NET 1.0也头脑的人,甚至在此之前:)

It is not that hard, keep in mind people used to do these kind of job in .Net 1.0 also, even before that :)

var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.ContinueWhenAll(runningTasks.ToArray(), antecedents =>
{
    webBrowser1.DocumentText = ...//This runs in UI thread
},CancellationToken.None, TaskContinuationOptions.None,uiTaskScheduler );

我缺少的东西?

Am I missing something?

这篇关于等待响应异步HTTP请求,而不异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆