0

I want to implement re-attempt logic for X amount of times to complete a single task.

Here is what I have done

private async Task ExecuteTasks(List<Task> tasks)
{
    foreach(var task in tasks)
    {
        // first attempt!
        await task;

        int failedCounter = 0;

        if(task.IsFaulted)
        {
            while(++failedCounter <= 3)
            {
                // Here retry the task.
                task.Start(); // this throws an exception.
            }
        }
    }
}

Calling task.Start() will throw an exception since the status is already faulted. How can I reset the status of a task? If this is not possible, how do I create a task from a previous failed task?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Jay
  • 1,168
  • 13
  • 41
  • 2
    Tasks aren't threads, they can't be restarted. There's no point in using `Task.Start` as if they were threads. They are *promises* that something will complete in the future. The Task/Promise may execute on an already existing Threadpool thread, or it may represent the completion of an IO or network operation, in which case it doesn't run anywhere – Panagiotis Kanavos Aug 24 '23 at 16:40
  • @PanagiotisKanavos thank you. Is there a way to create a new task from previously faulted task so the new task in run using a new promise? – Jay Aug 24 '23 at 16:41
  • 3
    The thing that needs to be retried is the *asynchronous function*, not the task. This could be as easy as `while(retries-->0){ await DoSomethingAsync(); return;}`. Libraries like [Polly](https://github.com/App-vNext/Polly) allow using complex retry strategies, with exponential delays, short-circuiting etc. .NET Core's HttpClientFactory integrates with Polly directly to implement retry strategies when calling remote APIs – Panagiotis Kanavos Aug 24 '23 at 16:43
  • Does this mean `await` will execute the action into a new task always? so adding `await task;` followed by `await task;` will execute the same callback using 2 promises? – Jay Aug 24 '23 at 16:46
  • 1
    `Is there a way to create a new task ...` that's the same question, reworded. I didn't use the word `Promise` by accident. In other languages, eg JavaScript, `Promise` is the actual word used for this. A Task only represents a Promise that something will complete in the future and *maybe* return a results, not the action itself – Panagiotis Kanavos Aug 24 '23 at 16:46
  • `await will execute` no, await *awaits* for that promise to complete, without blocking the current thread. Calling `await task` twice will only await once. The second time, the task is already completed. – Panagiotis Kanavos Aug 24 '23 at 16:48
  • 1
    So instead of looping through tasks, I should loop through callbacks which is used to create new task each time I want to execute the callback. yes? – Jay Aug 24 '23 at 17:00
  • 1
    *"Tasks aren't threads, they can't be restarted."* -- Threads can't be restarted either. – Theodor Zoulias Aug 24 '23 at 17:10

0 Answers0