使用ContinueWith函数使用C#的TaskFactory。我正试图解决这个问题
我开始的代码看起来像这样
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()和CheckIfExecutionWasSuccessful()看起来像这样
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()
有些东西告诉我,这不是解决这个问题的最好方法。有什么建议,想法吗?
答案 0 :(得分:3)
我不明白为什么要使用多个Task
和ContinueWith()
使这更复杂。相反,编写代码就像没有Task
和然后在Task
中运行它一样:
Task.Factory.StartNew(() =>
{
for (int i = 0; i < maxTries - 1; i++)
{
try
{
return Foo();
}
catch
{ }
}
return Foo();
});
这使代码更清晰,更明显更正确,更容易修改。
答案 1 :(得分:0)
简单:
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));