使用C#的异步WebRequest [英] Asynchronous WebRequests using C#

查看:487
本文介绍了使用C#的异步WebRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将url Get参数传递到Web服务器上的php文件并等待文件响应的函数(通常需要10到20秒).我想将其放入循环中,因为我必须立即将这些Get请求发送到大约5个不同的php文件中,但是当我尝试将其添加到循环中时,该功能会使循环一直等到文件返回响应后再去转到下一个.

Hi i have a function that passes url Get parameters to a php file on a webserver and waits for a response from the file (normally takes 10-20 seconds). I want to put this inside a loop because I have to send these Get requests to about 5 different php files at once but when i try to add it to a loop the function makes the loop wait until the file returns the response before it will go on to the next one.

    public string HttpGet(string URI, string Parameters)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI + Parameters);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader resStream = new StreamReader(response.GetResponseStream());
          return resStream.ReadToEnd().Trim();
    }

    private void SendCommand()
    {
        for( int i = 0; i <= 4; i++)
        {
            AddRTB(HttpGet(url, paramater));
        }
    }

有没有一种方法可以立即发送所有5个请求,而无需等待前一个请求完成? (我当时正在考虑对其进行线程化,但是我之前从未接触过它,因为我不知道从哪里开始.)

Is there a way that i could send the all 5 requests at once without waiting for the previous to finish? (i was thinking about threading it but alas i never touched it before is i don't know where to start.)

推荐答案

以下是使用TPL的两种方法.

Here are two approaches which uses the TPL.

第一个先等待所有请求完成,然后再访问任何结果

The first waits for all the requests to complete before you access any of the results

var runningTasks = new List<Task<string>>();

for (int ii = 0; ii <= 4; ii++)
{
    var wreq = (HttpWebRequest)WebRequest.Create("..." + ii);

    var taskResp = Task.Factory.FromAsync<WebResponse>(wreq.BeginGetResponse, 
                                                    wreq.EndGetResponse, 
                                                    null);
    var taskResult = taskResp.ContinueWith(tsk => new StreamReader(tsk.Result.GetResponseStream()).ReadToEnd().Trim());
    runningTasks.Add(taskResult);
}

Task.WaitAll(runningTasks.ToArray());
IEnumerable<string> results = runningTasks.Select(tsk => tsk.Result);

第二个结果对每个结果都做了一些处理:

and the second does something with each result as it comes in:

for (int ii = 0; ii <= 4; ii++)
{
    var wreq = (HttpWebRequest)WebRequest.Create("..." + ii);

    var taskResp = Task.Factory.FromAsync<WebResponse>(wreq.BeginGetResponse, 
                                                    wreq.EndGetResponse, 
                                                    null);
    taskResp.ContinueWith(tsk => new StreamReader(tsk.Result.GetResponseStream()).ReadToEnd().Trim())
            .ContinueWith((Task<string> trs) => 
                { 
                    var result = trs.Result;
                    DoSomthingWithTheResult(result);
                });
}

这篇关于使用C#的异步WebRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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