如果你不想使用async/await
你可以使用下面的擴展方法作爲起點。
static class HttpClientExtentions
{
public static Task<string> GetStringWithRetryAsync(this HttpClient client, string url, int retries)
{
var completion = new TaskCompletionSource<string>();
var ex = new List<Exception>();
Task<string> getString = client.GetStringAsync(url);
Action<Task<string>> continueAction = null;
continueAction = (t) =>
{
if (t.IsFaulted)
{
ex.Add(t.Exception);
if (retries-- > 0)
{
getString = client.GetStringAsync(url);
getString.ContinueWith(continueAction);
}
else
{
completion.SetException(new AggregateException(ex));
}
}
else // assume success, you could also handle cancellation
{
completion.SetResult(t.Result);
}
};
getString.ContinueWith(continueAction);
return completion.Task;
}
}
使用這種方式:
for (int i = 0; i < list.Count; i++)
{
var tuple = list[i];
string url = tuple.Item2;
int retryCount = 3;
var httpClient = new HttpClient(); // should create new object for each req
tasks[i] = httpClient.GetStringWithRetryAsync(url, retryCount).
ContinueWith(task => {
{
//......
});
}
Task.WaitAll(tasks);
來源
2014-10-13 09:17:08
YK1
如果重試失敗,你還想要一個例外? – i3arnon 2014-10-10 23:13:12
@ I3arnon:我知道。但是,這個異常將作爲AggregateException傳遞給Task.WaitAll。是對的嗎? – derekhh 2014-10-10 23:15:16
是的,因爲任務可能包含幾個例外。如果你'等待爲'async-await'構建的Task.WhenAll',那麼你會得到實際的異常(第一個是)。 – i3arnon 2014-10-10 23:17:04