For a while now I’ve been curi­ous as to whether the CLR uses the Thread­Pool to exe­cute a del­e­gate when Begin­In­voke is called:

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

Whilst com­mon sense dic­tates that this must surely be true, I couldn’t be cer­tain since I haven’t man­aged to find any con­fir­ma­tion in the documentations.

Thanks to Jon Skeet and Jeff Ster­nal who pro­vided the answer to my ques­tion and a link to the MSDN arti­cle which con­firms it:

If the Begin­In­voke method is called, the com­mon lan­guage run­time (CLR) queues the request and returns imme­di­ately to the caller. The tar­get method is called asyn­chro­nously on a thread from the thread pool.

This of course, means that if your del­e­gate is likely to take a while to exe­cute you should not call Begin­In­voke on the del­e­gate to avoid block­ing the Thread­Pool threads, instead you could cre­ate a new thread or use a Smart­Thread­Pool instance. I’ve dis­cussed these aspect in more detail here and here if you’re interested.

Ref­er­ences:

MSDN – Asyn­chro­nous Pro­gram­ming using Delegates

Stack­Over­flow Ques­tion – Does Func.BeginInvoke use the ThreadPool

Share

Leave a Reply