C#多个异步HttpRequest带有一个回调

aep*_*eus 9 c# asynchronous httprequest

我想一次发出10个异步http请求,只在完成所有结果并在单个回调函数中处理结果.我也不想使用WaitAll来阻止任何线程(我理解WaitAll会阻塞所有线程直到完成).我想我想制作一个可以处理多个调用的自定义IAsyncResult.我是在正确的轨道上吗?是否有任何好的资源或示例描述处理此问题?

Sco*_*t P 4

我喜欢达林的解决方案。但是,如果你想要更传统的东西,你可以尝试这个。

我肯定会使用等待句柄数组和 WaitAll 机制:

static void Main(string[] args)
{

    WaitCallback del = state =>
    {
        ManualResetEvent[] resetEvents = new ManualResetEvent[10];
        WebClient[] clients = new WebClient[10];

        Console.WriteLine("Starting requests");
        for (int index = 0; index < 10; index++)
        {
            resetEvents[index] = new ManualResetEvent(false);
            clients[index] = new WebClient();

            clients[index].OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);

            clients[index].OpenReadAsync(new Uri(@"http:\\www.google.com"), resetEvents[index]);
        }

        bool succeeded = ManualResetEvent.WaitAll(resetEvents, 10000);
        Complete(succeeded);

        for (int index = 0; index < 10; index++)
        {
            resetEvents[index].Dispose();
            clients[index].Dispose();
        }
    };

    ThreadPool.QueueUserWorkItem(del);

    Console.WriteLine("Waiting...");
    Console.ReadKey();
}

static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    // Do something with data...Then close the stream
    e.Result.Close();

    ManualResetEvent readCompletedEvent = (ManualResetEvent)e.UserState;
    readCompletedEvent.Set();
    Console.WriteLine("Received callback");
}


static void Complete(bool succeeded)
{
    if (succeeded)
    {
        Console.WriteLine("Yeah!");
    }
    else
    {
        Console.WriteLine("Boohoo!");
    }
}
Run Code Online (Sandbox Code Playgroud)