I am using Task.WaitAny to call 3 different methods (TrySolution1, TrySolution2 and TrySolution3) concurrently. My requirement is to find which method gets executed first and abort/cancel the other methods execution, If the first method returns result.
Tried using CancellationTokenSource to perform cancellation of the other tasks once the first method executes, but could see that the other methods still executes.
My code snippet:
Task<Boolean>[] tasks = new Task<Boolean>[3];
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
tasks[0] = Task<Boolean>.Factory.StartNew(() => TrySolution1());
tasks[1] = Task<Boolean>.Factory.StartNew(() => TrySolution2());
tasks[2] = Task<Boolean>.Factory.StartNew(() => TrySolution3());
Task.WaitAny(tasks, ct);
cts.Cancel();
You need to set the cancellation token to cancelled at the end of each attempt and then check for it in each method to see if it was cancelled at some point. Something like this...check out Task Cancellation
Be careful though. This will set the cancellation task, so although one task will complete the token will still be set.