Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Func<T>.BeginInvoke use the ThreadPool?

Tags:

When you call the BeginInvoke method on a Func delegates (or the Action delegates for that matter) in C#, does the runtime use the ThreadPool or spawn a new thread?

I'm almost certain that it'll use the ThreadPool as that'd be the logical thing to do but would appreciate it if someone could confirm this.

Thanks,

like image 201
theburningmonk Avatar asked Aug 24 '10 12:08

theburningmonk


People also ask

When should you not use Threadpool?

Thread pools do not make sense when you need thread which perform entirely dissimilar and unrelated actions, which cannot be considered "jobs"; e.g., One thread for GUI event handling, another for backend processing. Thread pools also don't make sense when processing forms a pipeline.

What is BeginInvoke?

BeginInvoke : This is a functionally similar to the PostMessage API function. It posts a message to the queue and returns immediately without waiting for the message to be processed. BeginInvoke returns an IAsyncResult , just like the BeginInvoke method on any delegate.

How do you use EndInvoke and Startinvoke?

BeginInvoke returns an IAsyncResult, which can be used to monitor the progress of the asynchronous call. The EndInvoke method retrieves the results of the asynchronous call. It can be called any time after BeginInvoke . If the asynchronous call has not completed, EndInvoke blocks the calling thread until it completes.


1 Answers

It uses the thread pool, definitely.

I'm blowed if I can find that documented anyway, mind you... this MSDN article indicates that any callback you specify will be executed on a thread-pool thread...

Here's some code to confirm it - but of course that doesn't confirm that it's guaranteed to happen that way...

using System;
using System.Threading;

public class Test
{
    static void Main()
    {
        Action x = () => 
            Console.WriteLine(Thread.CurrentThread.IsThreadPoolThread);

        x(); // Synchronous; prints False
        x.BeginInvoke(null, null); // On the thread-pool thread; prints True
        Thread.Sleep(500); // Let the previous call finish
    }
}

EDIT: As linked by Jeff below, this MSDN article 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.

like image 120
Jon Skeet Avatar answered Sep 20 '22 17:09

Jon Skeet