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

Does Funclt;Tgt;.BeginInvoke use the ThreadPool?(Funclt;Tgt;.BeginInvoke 使用线程池吗?)
本文介绍了Func<T>.BeginInvoke 使用线程池吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在 C# 中调用 Func 委托(或相关的 Action 委托)上的 BeginInvoke 方法时,运行时是使用 ThreadPool 还是生成新线程?

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?

我几乎可以肯定它会使用 ThreadPool,因为这是合乎逻辑的做法,但如果有人能证实这一点,我将不胜感激.

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.

谢谢,

推荐答案

肯定是用线程池的.

如果我能找到文档,我会感到震惊,请注意... 这篇 MSDN 文章 表明您指定的任何 回调 都将在线程池线程上执行...

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

如下面的 Jeff 所链接,这篇 MSDN 文章 证实它:

As linked by Jeff below, this MSDN article confirms it:

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

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 使用线程池吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)