代码之家  ›  专栏  ›  技术社区  ›  theburningmonk

Func<T>.BeginInvoke是否使用线程池?

  •  19
  • theburningmonk  · 技术社区  · 15 年前

    当您在C#中对Func委托(或操作委托)调用BeginInvoke方法时,运行时是使用ThreadPool还是生成新线程?

    2 回复  |  直到 15 年前
        1
  •  29
  •   Jon Skeet    15 年前

    不管怎样,如果我能找到文件,我真是气坏了,提醒你。。。 this MSDN article 表示任何 回拨 指定将在线程池线程上执行。。。

    这里有一些代码来证实这一点-但当然,这并不能证实它是正确的 放心

    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
        }
    }
    

    编辑:如下面杰夫所说, this MSDN article

    如果调用了BeginInvoke方法, 将请求排队并返回 立即通知来电者。目标 方法在上异步调用 线程池中的线程。

        2
  •  -6
  •   Khalid Abuhakmeh    15 年前

    以上是针对控件的,但也可以假定Func的功能相同。BeginInvoke允许您从另一个线程执行Func,但不会为您创建线程。所以乔恩·斯凯特是对的。除非您正在为异步执行创建线程,否则我甚至不会使用此功能,因为它不会为您带来任何东西,而不仅仅是调用Invoke。