In java it is possible to get a snapshot of the stacktraces of all running threads.
This is done with java.lang.Thread.getAllStackTraces() (it returns Map<Thread,StackTraceElement[]>).
How can this be done with .net?
In java it is possible to get a snapshot of the stacktraces of all running threads.
This is done with java.lang.Thread.getAllStackTraces() (it returns Map<Thread,StackTraceElement[]>).
How can this be done with .net?
If you want to get stack traces of all the threads within managed code then you could try mdbg. Have a look at Managed Stack Explorer it does use mdbg and gets stacks of all the threads.
Updated code to get a snapshot of all stack traces that uses the answer from @Joshua Evensen as a base. You'll still need to install NuGet package CLR Memory Diagnostics (ClrMD). This snippet also includes extra code to get the thread names, but this isn't required if you just want the stack traces.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.Diagnostics.Runtime;
namespace CSharpUtils.wrc.utils.debugging
{
public static class StackTraceAnalysis
{
public static string GetAllStackTraces()
{
var result = new StringBuilder();
using (var target = DataTarget.CreateSnapshotAndAttach(Process.GetCurrentProcess().Id))
{
var runtime = target.ClrVersions.First().CreateRuntime();
// We can't get the thread name from the ClrThead objects, so we'll look for
// Thread instances on the heap and get the names from those.
var threadNameLookup = new Dictionary<int, string>();
foreach (var obj in runtime.Heap.EnumerateObjects())
{
if (!(obj.Type is null) && obj.Type.Name == "System.Threading.Thread")
{
var threadId = obj.ReadField<int>("m_ManagedThreadId");
var threadName = obj.ReadStringField("m_Name");
threadNameLookup[threadId] = threadName;
}
}
foreach (var thread in runtime.Threads)
{
threadNameLookup.TryGetValue(thread.ManagedThreadId, out string threadName);
result.AppendLine(
$"ManagedThreadId: {thread.ManagedThreadId}, Name: {threadName}, OSThreadId: {thread.OSThreadId}, Thread: IsAlive: {thread.IsAlive}, IsBackground: {thread.IsBackground}");
foreach (var clrStackFrame in thread.EnumerateStackTrace())
result.AppendLine($"{clrStackFrame.Method}");
}
}
return result.ToString();
}
}
}
You can use ProcInsp, which has a web API to get threads with their stacks in JSON. The web API is available at /Process/%PID%/Threads (use a GET request).
Disclaimer: I'm the developer of ProcInsp. The tool is under the MIT licence and is free for use.
There is a StackTrace class
var trace = new System.Diagnostics.StackTrace(exception);
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
You can loop on System.Diagnostics.Process.GetCurrentProcess().Threads and for each Thread create a StackTrace object with the .ctor that takes a Thread as its param.