虽然您可以使用事件,但我建议在类Task<T>
上使用和FromAsync
方法,如下所示:TaskFactory
// 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
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.
});
请注意,上面的返回 aTask
完成后您将不得不等待或继续(如果您担心通知)。
如果您使用的是 .NET 4.5,则不需要使用类ContinueWhenAll
上的方法TaskFactory
,但可以使用类上的WhenAll
方法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.
请注意,上面的内容是在显示正在使用 .NET 3.5之前。