This question already has an answer here:
There are three tasks that I wish to run in parallel. I wish to examine the result of the first task that finished and do a check to decide if the result is good. If yes, I cancel all other tasks and return this result, if not, I will wait for next completed task and check if that is good and do the same if it is. (Think of being good as some simple check on a member of OutputDataType).
I continue this until I obtain a completed task with a good result, or all tasks return with results that are not good, in which case I return null
.
Thank you in advance.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace myNamespace
{
class Program
{
static void Main()
{
InputDataType data = getMyData();
OutputDataType x = Foo(data);
}
static OutputDataType Foo(InputDataType data)
{
Task<OutputDataType> task1 = null, task2 = null, taks3 = null;
Task<OutPutDataType>[] TaskArray = { task1, task2, task3 };
task1 = Task<SolutionInterpreters>.Factory.StartNew(() => RunFunc1(data));
task2 = Task<SolutionInterpreters>.Factory.StartNew(() => RunFunc2(data));
task3 = Task<SolutionInterpreters>.Factory.StartNew(() => RunFunc3(data));
/*
.
.
.
*/
}
}
}
In TPL, task cancellation is cooperative, so you need to define some means of indicating to your other tasks that they should stop executing. The most common way to do this is through
CancellationTokenSource
, whose token can be checked for cancellation within yourRunFuncX
methods.Per Spo1ler's comment, I've updated your
Foo
method to an asynchronous implementation. This assumes you're using C# 5.0. When consuming the method, useawait
to get its result. If you're really running as a console application, your topmost call would need to block, so you can just get the task'sResult
.