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,
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With