Skip to content

Instantly share code, notes, and snippets.

@kevinswiber
Created March 20, 2011 05:54
Show Gist options
  • Save kevinswiber/878136 to your computer and use it in GitHub Desktop.
Save kevinswiber/878136 to your computer and use it in GitHub Desktop.
Example of sharing stack traces between threads.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace StackTraceSharing
{
public class Program
{
static void Main(string[] args)
{
const int numberOfThreads = 5;
for (var threadIndex = 0; threadIndex < numberOfThreads; threadIndex++)
{
var thread = new Thread(new ThreadStart(() =>
{
var threadId = Thread.CurrentThread.ManagedThreadId;
ThreadRegistry.Add(threadId);
StackTraceRegistry.Add(threadId, new StackTrace(true));
Console.WriteLine("Added thread: " + threadId);
var otherThreads = ThreadRegistry.Except(threadId);
if (otherThreads.Any())
{
var otherThread = otherThreads.Last();
var stackTrace = StackTraceRegistry.Get(otherThread);
Console.WriteLine("Other Thread: " + otherThread);
Console.WriteLine("Other Thread's StackTrace FrameCount: " + stackTrace.FrameCount);
}
}));
thread.Start();
}
Console.ReadKey();
}
}
public static class ThreadRegistry
{
private static object _lock = new object();
private static List<int> _threadIds = new List<int>();
public static void Add(int threadId)
{
lock (_lock)
{
_threadIds.Add(threadId);
}
}
public static IEnumerable<int> Except(int threadId)
{
lock (_lock)
{
return _threadIds.Except(new[] {threadId});
}
}
}
public static class StackTraceRegistry
{
private static object _lock = new object();
private static IDictionary<int, StackTrace> _stackTraces = new Dictionary<int, StackTrace>();
public static void Add(int threadId, StackTrace stackTrace)
{
lock (_lock)
{
_stackTraces.Add(threadId, stackTrace);
}
}
public static StackTrace Get(int threadId)
{
lock (_lock)
{
if (_stackTraces.ContainsKey(threadId))
{
return _stackTraces[threadId];
}
throw new ArgumentException(string.Format("Thread ID '{0}' has not been added to the registry.", threadId), "threadId");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment