Darko
Darko

Reputation: 527

killing threads from main

I am a bit new to threading as I have never needed it on an advanced level up until now.

I have the following problem I need to solve:

I have an application where you specify how many threads it should work with, and after that you get it to start.

I know this can be done with ThreadPool but I need a bit more functionality, I don't know how to make it so it makes a callback when all the threads are done and a function to stop all threads and queues if needed.

One idea was making a new thread and working with the threadpool from there so that when I kill that threat it kills are the ones started from that thread (being the main). Also that way I'd be able to set it to call back (the single thread) when the queue is cleared.

Upvotes: 0

Views: 176

Answers (1)

Tyson
Tyson

Reputation: 14734

You could use Tasks and CancellationTokens:

        var taskCount = 10;
        var cancellationTokenSource = new CancellationTokenSource();
        for (int i = 0; i < taskCount ; i++)
        {
            var cancellationToken = cancellationTokenSource.Token;
            Task.Factory.StartNew(() =>
            {
                // do work here.

                // Also periodically check 
                if( cancellationToken.IsCancellationRequested )
                    return;

                // or wait on wait handle
                cancellationToken.WaitHandle.WaitOne(timeout);
            }, cancellationToken);
        }

        // to cancel all threads 
        cancellationTokenSource.Cancel();

The number of threads running concurrently is managed for you by the ThreadPool within the TaskFactory, based on your machine's reported CPU cores. If you want more control, it is possible to provide your own custom TaskFactories I believe.

Upvotes: 3

Related Questions