In my application I have a List<Task<Boolean>>
that I Task.Wait[..]
on to determine if they completed successfully (Result = true
). Though if during my waiting a Task
completes and returns a falsey value I want to cancel all other Task
I am waiting on and do something based on this.
I have created two "ugly" methods to do this
// Create a CancellationToken and List<Task<..>> to work with
CancellationToken myCToken = new CancellationToken();
List<Task<Boolean>> myTaskList = new List<Task<Boolean>>();
//-- Method 1 --
// Wait for one of the Tasks to complete and get its result
Boolean finishedTaskResult = myTaskList[Task.WaitAny(myTaskList.ToArray(), myCToken)].Result;
// Continue waiting for Tasks to complete until there are none left or one returns false
while (myTaskList.Count > 0 && finishedTaskResult)
{
// Wait for the next Task to complete
finishedTaskResult = myTaskList[Task.WaitAny(myTaskList.ToArray(), myCToken)].Result;
if (!finishedTaskResult) break;
}
// Act on finishTaskResult here
// -- Method 2 --
// Create a label to
WaitForOneCompletion:
int completedTaskIndex = Task.WaitAny(myTaskList.ToArray(), myCToken);
if (myTaskList[completedTaskIndex].Result)
{
myTaskList.RemoveAt(completedTaskIndex);
goto WaitForOneCompletion;
}
else
;// One task has failed to completed, handle appropriately
I was wondering if there was a cleaner way to do this, possibly with LINQ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…