Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
363 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...