2012-01-20 7 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]--; 
    } 
} 

を使用すると、再気にしないのであれば - しかし、同時にたくさんのことを期待していますが、毎回合計をチェックしたくない場合は、ストライプカウンタを使用してください。これは、低競合ではかなり遅くなりますが、コア間の競合が非常に速く、あなたのケースにも適用可能です。

関連する問題