Restart the task if it fails

I am trying to restart one of several tasks if it fails. I'm using .ContinueWith(t => { HandleException(t); }, TaskContinuationOptions.OnlyOnFaulted);

where the method is HandleException(t)

to find the task in the excisting array of tasks and create a new one in its place. Only the task passed to my method HandleException(t)

is different from the original task, so I cannot find it in my tasks. Also the exclusive task is still running while the exception is being handled.

Example:

using System;
using System.Threading.Tasks;
using System.Threading;

static Task[] tasks;
static void Main(string[] args)
{
    tasks = new Task[2];
    for (int i = 0; i < tasks.Count(); i++)
    {
        tasks[i] = Task.Run(() => { Thread.Sleep(1000); throw new Exception("BOOM"); })
             .ContinueWith(t => { HandleException(t); }
             , TaskContinuationOptions.OnlyOnFaulted);

        Console.WriteLine(String.Format("Task {0} started", tasks[i].Id));
    }

    Console.ReadLine();
}

static void HandleException(Task task)
{
    Console.WriteLine(String.Format("Task {0} stopped", task.Id));

    // Check task status
    for (int i = 0; i < tasks.Count(); i++)
    {
        Console.WriteLine(String.Format("Task {0} status = {1}", i, tasks[i].Status));
    }
    // fFind and restart the task here
    if (tasks.Contains(task))
    {
        int index = Array.IndexOf(tasks, task);
        tasks[index] = Task.Run(() => { Thread.Sleep(1000); throw new Exception("BOOM"); })
         .ContinueWith(t => { HandleException(t); }
         , TaskContinuationOptions.OnlyOnFaulted);

        Console.WriteLine(String.Format("Task {0} started", tasks[index].Id));
    }
}

      

My application results in:

Task 3 started
Task 6 started
Task 5 stopped
Task 0 status = Running
Task 2 stopped
Task 1 status = Running
Task 0 status = Running
Task 1 status = Running

      

Since the task passed to HandleException(t)

is different from the original task, it is not found in tasks[]

and thus does not restart. Also looking at the states tasks[]

, it hasn't stopped yet. How can I properly restart my task?

+3


source to share


1 answer


This is because you are storing the continuation task in your array, not the original task (that is - you are storing the result ContinueWith

). To fix, save the original task instead:



var task = Task.Run(() => { Thread.Sleep(1000); throw new Exception("BOOM");});
task.ContinueWith(t => { HandleException(t); }
         , TaskContinuationOptions.OnlyOnFaulted);
tasks[i] = task;

      

+4


source







All Articles