线程池中的活动线程号

Yag*_*urk 7 c# threadpool

当我编写下面的代码时,为什么我得到可用的线程编号,如1022,1020.我必须得到25个线程最大,因为我使用线程池.

我猜输出线程号是系统上的可用线程.我需要在win表单应用程序中的线程池中获取可用的线程号.

private void Foo()
{
    int intAvailableThreads, intAvailableIoAsynThreds;

    // ask the number of avaialbe threads on the pool,
    //we really only care about the first parameter.
    ThreadPool.GetAvailableThreads(out intAvailableThreads,
        out intAvailableIoAsynThreds);

    // build a message to log
    string strMessage =
        String.Format(@"Is Thread Pool: {1},
            Thread Id: {2} Free Threads {3}",
            Thread.CurrentThread.IsThreadPoolThread.ToString(),
            Thread.CurrentThread.GetHashCode(),
            intAvailableThreads);

    // check if the thread is on the thread pool.
    Trace.WriteLine(strMessage);

    // create a delay...
    Thread.Sleep(30000);

    return;
}
Run Code Online (Sandbox Code Playgroud)

非常感谢..

(注意:我从http://www.codeproject.com/KB/cs/AsyncMethodInvocation.aspx获得了代码)很好的文章!!

Jon*_*eet 9

当我使用线程池时,我必须获得25个最大线程.

每个核心的线程池中的最大线程数随着时间的推移而发生了很大变化.它不再是每个核心25个,我怀疑这是你所期待的.

例如,在我使用.NET 4的四核超线程笔记本电脑上运行它,我得到最多32767个工作线程和1000个IO完成端口线程:

using System;
using System.Threading;

class Test
{
    static void Main()
    {
        int worker; 
        int ioCompletion;
        ThreadPool.GetMaxThreads(out worker, out ioCompletion);
        Console.WriteLine("{0} / {1}", worker, ioCompletion);
    }    
}
Run Code Online (Sandbox Code Playgroud)

在.NET 3.5下,我获得了2000个工作线程,仍然有1000个IO完成端口线程.

这不是线程池中实际存在的线程数 - 它是线程池允许自己随时间创建的最大数量.


Joh*_*len 5

使用ThreadPool.GetMaxThreads得到你想要的东西.

本文有助于解释您需要了解的所有内容ThreadPool.

  • @Rory,或者,这个答案似乎只是一个链接,应该是一条评论。 (2认同)