2012-01-20 91 views
7

我一直在寻找这个答案的网络,并找不到任何真正使我自己。我的方法有多少个线程?

我有一个程序,我正在运行,我想在给定的时间计算我的方法中有多少个线程。

我有一些代码在我的main()函数:

Parallel.Invoke(MyMethod,MyMethod,MyMethod,MyMethod); 


private static void MyMethod() 
{ 
    //how many threads are waiting here??? <--- this is what I am after 
    lock (myObj) 
    { 
     //one thread at a time please 
    } 
} 

任何人都可以在这里阐明?

+0

要清楚的是,您是否希望在程序中运行的另一个线程中查看此信息,或者只是在调试时查看并查看,并且需要查找在Visual Studio中的何处找到它? –

+2

我不认为这是一个好主意,跟踪这些信息,并根据他们。如果你在生产代码中需要这样的东西,那么很可能你的设计有问题。 – Zuljin

+0

@Zuljin登录以帮助查找设计的错误可能很有用。 –

回答

12

没有办法直接查询给定函数中有多少个线程。唯一的办法是做手工跟踪

private static int s_threadCount; 

private static void MyMethod() { 
    Interlocked.Increment(ref s_threadCount); 
    try { 
    ... 
    } finally { 
    Interlocked.Decrement(ref s_threadCount); 
    } 
} 

注:如果此方法可以递归进入这不会准确计数的线程数量,而是将计算线程的数量+的时候,他们进入递归函数。

+0

这将解释为什么我找不到它:)谢谢! – user1158555

3

这样做会增加一个计数器的唯一方法:

static int counter; 
... 
static void SomeMethod() { 
    int threadsInMethod = Interlocked.Increment(ref counter); 
    try { 
     code here 
    } finally { 
     Interlocked.Decrement(ref counter); 
    } 
} 

警告:如果该方法被重入将同时嵌套超量本身。

1

不奢望很多同时进入/离开和不关心重入:

static int _cThreads; 
static void SomeMethod() 
{ 
    Interlocked.Increment(ref _cThreads); 
    try 
    { 
    /* blah */ 
    } 
    finally 
    { 
    Interlocked.Decrement(ref _cThreads); 
    } 
} 

做一下重入护理:

static IDictionary<int, int> _cThreads; // ConcurrentDictionary or alternative thread-safe dictionary 
static void SomeMethod() 
{ 
    if(_cThreads.ContainsKey(Thread.CurrentThread.ManagedThreadId))//note that only this thread will hit this key 
    _cThreads[Thread.CurrentThread.ManagedThreadId]++ 
    else 
    _cThreads[Thread.CurrentThread.ManagedThreadId] = 1; 
    try 
    { 
    /* blah */ 
    //When I care about the count then it's _cThreads.Values.Where(v => v != 0).Count() 
    //which will mutate while we're trying to count it, but then any 
    //answer to this is going to have a degree of staleness 
    /*blah*/ 
    } 
    finally 
    { 
    _cThreads[Thread.CurrentThread.ManagedThreadId]--; 
    } 
} 

如果你不关心重-entrancy,但期待很多同时进行,但不希望每次都检查总数,然后使用条形计数器。这种情况在竞争较少的情况下会明显变慢,但核心之间的争用速度要快得多,并且可能适用于您的情况。