the*_*onk 20 .net c# multithreading delegates
当您在C#中调用Func委托(或Action代理)上的BeginInvoke方法时,运行时是否使用ThreadPool或生成新线程?
我几乎可以肯定它会使用ThreadPool,因为这是合乎逻辑的事情,但如果有人能证实这一点,我会很感激.
谢谢,
Jon*_*eet 29
它绝对使用线程池.
如果我能找到记录的话,我很震惊,请注意...... 这篇MSDN文章指出你指定的任何回调都将在线程池线程上执行...
这里有一些代码可以确认它 - 但当然这并不能证实它确保以这种方式发生......
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
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:由下面的杰夫链接,这篇MSDN文章证实了这一点:
如果调用BeginInvoke方法,则公共语言运行库(CLR)将请求排队并立即返回给调用者.目标方法在线程池的线程上异步调用.