Func< T> .BeginInvoke使用ThreadPool? [英] Does Func<T>.BeginInvoke use the ThreadPool?

查看:139
本文介绍了Func< T> .BeginInvoke使用ThreadPool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在C#中的Func代理(或Action代理)上调用BeginInvoke方法时,运行时是否使用ThreadPool或生成新线程?



我几乎肯定会使用ThreadPool,因为这是合乎逻辑的事情,但如果有人可以确认,会感激。



谢谢

解决方案

它使用线程池,绝对。



如果我能找到记录的话,打扰你,记住你... 这个MSDN文章表示您指定的任何回调将在线程池线程上执行...



这是一些代码来确认 - 但是当然这并不能证实这样做是为了保证的发生。

 使用系统; 
使用System.Threading;

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

x(); //同步;打印False
x.BeginInvoke(null,null); //在线程池线程上;打印True
Thread.Sleep(500); //让上一个通话完成
}
}

编辑:链接由Jeff在下面此MSDN文章确认:


如果调用BeginInvoke方法,
公共语言运行时(CLR)
将请求排队并立即返回
来电者目标
方法从线程池的
线程异步调用。



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,

解决方案

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.

这篇关于Func< T> .BeginInvoke使用ThreadPool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆