Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop all tasks when one is finished in c#

I have different tasks to read from different files and find a word into them. I have put them into a task array which I start with waitAny method as following :

foreach (string file in filesList)
        {
            files[i] = Task.Factory.StartNew(() =>
            {
                mySearch.Invoke(file);
            });
            i++;
        }
        System.Threading.Tasks.Task.WaitAny(files);

I would like to stop all other tasks as soon as one of the tasks finishes (it finishes when it founds the word). For the moment, with waitany, i can know when one tasks finishes, but I don't know how I could know which one has finished and how to stop other tasks. What would be the best way to achieve this ?

like image 452
Rayjax Avatar asked Nov 29 '12 16:11

Rayjax


People also ask

How to cancel an async task?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.

How do you terminate a task in C#?

In the newer library, TPL (System. Threading. Tasks), there is no direct method which cancels or aborts the underlying thread. But there is a way to cancel a task by using CancellationTokenSource class which allows you to pass the CancellationToken as one of the input parameters when you create the task.

What is TaskCompletionSource C#?

In many scenarios, it is useful to enable a Task<TResult> to represent an external asynchronous operation. TaskCompletionSource<TResult> is provided for this purpose. It enables the creation of a task that can be handed out to consumers.

What is task factory StartNew?

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.


1 Answers

When creating a Task you can pass a CancelationToken. Set this token when one of the tasks finishes. This will cause remaining tasks with this token to not execute. Running tasks can receive a OperationCanceledException and stop too.

like image 121
Blachshma Avatar answered Oct 06 '22 20:10

Blachshma