What happens if you start too many threads?

Viewed 9548

What happens when you create too many threads? Does it cause the CPU to crash or is there some sort of internal load balancing mechanism on Windows OS'?

I'm running the following code:

private async void A(string[] a)
{
    var tasks = a.Select(B);
    await Task.WhenAll(tasks);
}

private async Task B(string b)
{
    new Thread(async delegate ()
    {
        //all the work that needs to be done

    }).Start();
}

I'm running an array of async Tasks but within each async method I've encapsulated all the work that needs to be done in a new thread. What happens if I call B a large number of times? How will the processor deal with too many threads?

3 Answers

Threads do have significant costs - VERY roughly - imagine 100K bytes per thread (they each need a stack for one thing), and they each place a slight burdon on operating system components (e.g. scheduler) which have to manage them all.

Threads DO present a very simple model for managing async tasks. I'm a big fan of that approach.

But if you are going to use a lot of threads, please consider using thread pools as a way to re-use the underlying thread objects (while having lots of runnables - just not running).

And - since you are using C#, async tasks (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/) are a more efficient stategy to consider.

Often though - simplicity of implementation matters more than efficiency (up to a point). What you described with a thread-pool (to throttle actual thread count) may work fine.

Related