.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.
  2. Consulting: If you want to improve feature velocity, reduce costs, and make your systems more scalable, secure, and resilient, then let’s work together and make it happen.
  3. Join my FREE Community on Skool, where you can ask for help, share your success stories and hang out with me and other like-minded people without all the negativity from social media.

 

Leave a Comment

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