gpt4 book ai didi

C# 多个异步 HttpRequest 与一个回调

转载 作者:太空狗 更新时间:2023-10-29 17:51:19 25 4
gpt4 key购买 nike

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

最佳答案

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

我肯定会使用等待句柄数组和 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!");
}
}

关于C# 多个异步 HttpRequest 与一个回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2923041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com