Karthik Balasubramanian
Karthik Balasubramanian

Reputation: 1157

How to run a Task N times until it succeeds?

Am working with C#'s TaskFactory using ContinueWith function. The issue am trying to solve it this

The code I started with looks like this

var executeTask = Task.Factory.StartNew<ExecutionStatus>(() =>
        {
            return Foo();
        });
        executeTask.ContinueWith(task => CheckIfExecutionWasSuccessful(task)).
                        ContinueWith(task => CheckIfExecutionWasSuccessful(task)).
                        ContinueWith(task => CheckIfExecutionWasSuccessful(task)).
                        ContinueWith(task => CheckLastTimeBeforeGivingUp(task));

Foo() and CheckIfExecutionWasSuccessful() looks like this

ExecutionStatus Foo(){
      //Do my work
      return new ExecutionStatus(){Succeded = true}
     }

ExecutionStatus CheckIfExecutionWasSuccessful(Task<ExecutionStatus> task){
            if(task.Result.Succeeded) return task.Result;
            else return Foo()

Something tells me that this is not the best way to go about this problem. Any suggestions, ideas?

Upvotes: 1

Views: 547

Answers (2)

svick
svick

Reputation: 244797

I don't understand why are you making this more complicated by using multiple Tasks and ContinueWith(). Instead, write the code just like you would without Tasks and then run it in a Task:

Task.Factory.StartNew(() =>
{
    for (int i = 0; i < maxTries - 1; i++)
    {
        try
        {
            return Foo();
        }
        catch
        { }
    }

    return Foo();
});

This makes the code clearer, more obviously correct and easier to modify.

Upvotes: 3

Radu Porumb
Radu Porumb

Reputation: 785

Simple:

var MaxTries = 3;
var executeTask = Task.Factory.StartNew<ExecutionStatus>(() => Foo());

for(var i = 0; i < MaxTries; i++)
{
    executeTask = executeTask.ContinueWith(task => CheckIfExecutionWasSuccessful(task));
}

executeTask = executeTask.ContinueWith(task => CheckLastTimeBeforeGivingUp(task));

Upvotes: 0

Related Questions