views:

616

answers:

3

It is possible to get stacktrace using System.Diagnostics.StackTrace, but thread has to be suspended. Suspend and Resume function are obsolete, so I expect that better way exists.

+1  A: 

I think that if you want to do this without the cooperation of the target thread (such as by having it call a method that blocks it on a Semaphore or something while your thread does the stacktrace) you'll need to use the deprecated APIs.

A possible alternative is the use the COM-based ICorDebug interface that the .NET debuggers use. The MDbg codebase might give you a start:

Michael Burr
No, COM is not an option. Suspend/Resume feels way cleaner than COM stuff from .NET...
bh213
+2  A: 

According to C# 3.0 in a Nutshell, this is one of the few situations where it is okay to call Suspend/Resume.

Brian Rasmussen
That is what I ended up doing.
bh213
Be careful not to introduce deadlocks tough. If you suspend a thread while it is holding a lock you need, you'll have a deadlock. The most common cause would probably be if the threads share a stream (e.g. writing to the console or similar).
Brian Rasmussen
A: 

This is an old Thread, but just wanted to warn about the proposed solution: The Suspend and Resume solution does not work - I just experienced a deadlock in my code trying the sequence Suspend/StackTrace/Resume.

The Problem is that StackTrace constructor does RuntimeMethodHandle -> MethodBase conversions, and this changes a internal MethodInfoCache, which takes a lock. The deadlock occurred because the thread I was examining also was doing reflection, and was holding that lock.

It is a pity that the suspend/resume stuff is not done inside the StackTrace constructor -then this problem could easily have been circumvented.

Dirk Bonné