How to use Task.WhenAny and implement retry

前端 未结 2 978
失恋的感觉
失恋的感觉 2021-01-22 20:50

I have a solution that creates multiple I/O based tasks and I\'m using Task.WhenAny() to manage these tasks. But often many of the tasks will fail due to network issue or reques

2条回答
  •  借酒劲吻你
    2021-01-22 20:57

    I believe it would be easier to retry within the tasks, and then replace the Task.WhenAny-in-a-loop antipattern with Task.WhenAll

    E.g., using Polly:

    var tasks = new List>();
    var policy = ...; // See Polly documentation
    foreach(var item in someCollection)
      tasks.Add(policy.ExecuteAsync(() => GetSomethingAsync()));
    await Task.WhenAll(tasks);
    

    or, more succinctly:

    var policy = ...; // See Polly documentation
    var tasks = someCollection.Select(item => policy.ExecuteAsync(() => GetSomethingAsync()));
    await Task.WhenAll(tasks);
    

提交回复
热议问题