我正在发送大量的客户端get请求,并且以下代码可以正常工作,但是一旦找到StatusCode.OK的HttpResponseMessage后,如何强制执行停止,然后返回该单个Task。
public List<Task<HttpResponseMessage>> GetUploadURLAsync(List<string> list)
{
List<Task<HttpResponseMessage>> tasks = new List<Task<HttpResponseMessage>>();
using (HttpClient client = new HttpClient())
{
for(int i = 0; i < list.Count; i++)
{
<client get async code generating task list>
}
Task.WaitAll(tasks.ToArray());
}
return tasks;
}
答案 0 :(得分:1)
类似这样的东西:
class SomeClass
{
private static HttpClient _httpClient = new HttpClient();
public static Task<HttpResponseMessage> GetFirstSuccessAsync(List<string> list)
{
var tasks = new List<Task<HttpResponseMessage>>();
foreach (var url in list) {
tasks.Add(_httpClient.GetAsync(url));
}
return WhenAnySuccess(tasks);
}
private static async Task<HttpResponseMessage> WhenAnySuccess(List<Task<HttpResponseMessage>> tasks)
{
while (tasks.Count > 0) {
Task<HttpResponseMessage> task = await Task.WhenAny(tasks);
if (task.Status == TaskStatus.RanToCompletion && task.Result.StatusCode == HttpStatusCode.OK) {
return task.Result;
}
tasks.Remove(task);
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
var response = SomeClass.GetFirstSuccess(new List<string> { "http://google.com", "http://microsoft.com" }).Result;
Console.WriteLine(response.RequestMessage.RequestUri);
Console.ReadKey();
}
}
答案 1 :(得分:0)
假设您的异步操作支持取消操作,则需要CancellationTokenSource。