Reputation: 1157
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
Reputation: 244797
I don't understand why are you making this more complicated by using multiple Task
s and ContinueWith()
. Instead, write the code just like you would without Task
s 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
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