.Net Threading – BeginInvoke uses the thread pool

Yan Cui

I help clients go faster for less using serverless technologies.

For a while now I’ve been curious as to whether the CLR uses the ThreadPool to execute a delegate when BeginInvoke is called:

private void InvokeFunc(Func<int> func)
{
    func.BeginInvoke(null, null); // does this execute on a threadpool thread?
}

Whilst common sense dictates that this must surely be true, I couldn’t be certain since I haven’t managed to find any confirmation in the documentations.

Thanks to Jon Skeet and Jeff Sternal who provided the answer to my question and a link to the MSDN article which confirms it:

If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller. The target method is called asynchronously on a thread from the thread pool.

This of course, means that if your delegate is likely to take a while to execute you should not call BeginInvoke on the delegate to avoid blocking the ThreadPool threads, instead you could create a new thread or use a SmartThreadPool instance. I’ve discussed these aspect in more detail here and here if you’re interested.

References:

MSDN – Asynchronous Programming using Delegates

StackOverflow Question – Does Func.BeginInvoke use the ThreadPool

Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

Leave a Comment

Your email address will not be published. Required fields are marked *