Skip to content

Instantly share code, notes, and snippets.

@OmerMor
Created May 3, 2012 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save OmerMor/2587063 to your computer and use it in GitHub Desktop.
Save OmerMor/2587063 to your computer and use it in GitHub Desktop.
Answer to http://stackoverflow.com/q/10432494/61061: observing the death of client threads
using System;
using System.Threading;
namespace ThreadingTest
{
public class ThreadMonitor
{
public static event Action<int> Finalized = delegate { };
private readonly int m_threadId = Thread.CurrentThread.ManagedThreadId;
~ThreadMonitor()
{
Finalized(ThreadId);
}
public int ThreadId
{
get { return m_threadId; }
}
}
public static class Test
{
private readonly static ThreadLocal<ThreadMonitor> s_threadMonitor =
new ThreadLocal<ThreadMonitor>(() => new ThreadMonitor());
public static void Main()
{
ThreadMonitor.Finalized += i => Console.WriteLine("thread {0} closed", i);
var thread = new Thread(() =>
{
var threadMonitor = s_threadMonitor.Value;
Console.WriteLine("start work on thread {0}", threadMonitor.ThreadId);
Thread.Sleep(1000);
Console.WriteLine("end work on thread {0}", threadMonitor.ThreadId);
});
thread.Start();
thread.Join();
// wait for GC to collect and finalize everything
GC.GetTotalMemory(forceFullCollection: true);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment