Created
May 3, 2012 16:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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