Skip to main content
 首页 » 编程设计

c#之Web 应用程序中的 BeginGetResponse

2024年02月02日2698°冷暖

我想使用 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 method在 Task 上执行工作的类:

// 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之前的.