views:

215

answers:

3

Is there any tool available to profile .Net Thread contention. I have added performance counter for threads for a windows Service which is running slow. It shows around 150 thread contentions. I would like to profile what area of the code is responsible for so much of Thread contentions. Is there any tool available which can point me into the right code blocks.

A: 

Not a profiler, but windbg with the sosex.dll extension can tell you what deadlocks you are having. Look for it here and read about the !dlk command.

Otávio Décio
+1  A: 

Visual Studio 2010 has a thread contention profiler.

Mauricio Scheffer
Yes I am looking for something like that. But unfortunately I am on VS.Net 2005
Amitabh
@Amitabh: you can download VS2010 here: http://msdn.microsoft.com/en-us/vstudio/dd582936.aspx
Mauricio Scheffer
@Mauricio: I am working on a legacy application with huge code base. Unless it is decided from upper management to migrate the code base to newer version I have to live with Visual Studio 2005.
Amitabh
VS2010 can target .NET 2.0. You only need to upgrade the project files (.csproj, .vbproj) and solutions (.sln). No code migration is necessary. I'm not sure if you can use the profiler with .NET 2.0 projects though, but it's worth the shot I guess.
Mauricio Scheffer
A: 

I ran into the same problem with a Visual Studio 2008 project, so I wasn't able to use VS2010's thread contention profiler. Instead, I wrote a diagnostic class, TimedMonitor, that tracks the amount of time spent waiting for locks.

To use it, you would replace:

object myLock = new object();
lock (myLock) { /* do work */ }

with:

TimedMonitor timedLock = new TimedMonitor();
using (timedLock.Lock()) { /* do work */ }
Console.WriteLine("Lock was entered {0} times; total wait time: {1}.",
  timedLock.EnterCount, timedLock.WaitTime);

If you're only using a small number of simple locks (i.e., with Monitor.Enter or the lock keyword), replacing them with TimedMonitor and logging the output may help identify which lock is responsible for the most time spent waiting. However, if you're using more complex managed locks (e.g., ReaderWriterLock) or native synchronization (e.g., ManualResetEvent), it won't be helpful since it doesn't track those.

Bradley Grainger