gpt4 book ai didi

c# - Web 应用程序中的 BeginGetResponse

转载 作者:太空宇宙 更新时间:2023-11-03 20:24:25 24 4
gpt4 key购买 nike

我想使用 BeginGetResponse 方法来调用列表中的许多 URL。我有 2 个关于如何实现这个的问题:

  1. 根据 http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse(v=vs.95).aspx 中的示例

我们使用:

public static ManualResetEvent allDone= new ManualResetEvent(false);

在 Web 应用程序中使用静态成员是否明智,因为它与其他线程共享?这会导致问题吗?

  1. 我如何判断所有回调何时完成?我需要做一个结果总结报告

谢谢

最佳答案

虽然您可以使用事件,但我建议您使用 Task<T> FromAsync method TaskFactory class 上像这样:

// Execution of tasks starts here because of the
// call to ToArray.
Task<WebResponse>[] tasks = uris.Select(u => {
// Create the request.
WebRequest req = ...;

// Make the call to return the response asynchronously with
// a Task.
return Task.Factory.FromAsync(req.BeginGetResponse,
req.EndGetResponse, null);
}).ToArray();

一旦有了它,您就可以轻松地等待所有 Task<T>使用 ContinueWhenAll method 的实例在 TaskFactory 上像这样继续上课:

Task.Factory.ContinueWhenAll(tasks, t => {
// Note that t is an array of Task, so you have to cast
// each element to a Task<WebRequest>.
// Process all of them here.
});

注意上面返回一个 Task 完成后您将不得不等待或继续(如果您担心通知)。

如果您使用的是 .NET 4.5,则不需要使用 ContinueWhenAll TaskFactory 上的方法类,但可以使用 WhenAll methodTask 上执行工作的类:

// Note that work does not start here yet because of deferred execution.
// If you want it to start here, you can call ToArray like above.
IEnumerable<Task<WebResponse>> tasks = uris.Select(u => {
// Create the request.
WebRequest req = ...;

// Make the call to return the response asynchronously with
// a Task.
return Task.Factory.FromAsync(req.BeginGetResponse,
req.EndGetResponse, null);
});

// Execution will start at this call:
Task<Task<WebRequest>[]> allTasks = Task.WhenAll(tasks);

// Continue or wait here.

注意上面是it was revealed that .NET 3.5 was being used之前的.

关于c# - Web 应用程序中的 BeginGetResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11420252/

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