In the code sample that started these recent blog posts, I was using GetHashCode() to display a unique value for a thread in a simple example, for visually unique identifier for a thread, without bothering to set the Thread.Name property. For this simple type of example, GetHashCode() has always done the trick (and I've always referred to this as the logical thread ID) because I didn't care if I was displaying the physical (Win32) thread ID, accessible via AppDomain.GetCurrentThreadId(). In an application that requires maintenance of a list of running threads, I usually set the Name of each thread (better for debugging as well) and hold on to each Thread reference:
ThreadStart del = new ThreadStart(Start);Thread t = new Thread(del);m_newThreads.Add(t); // ArrayList scoped globallyt.Name="Thread #" + m_newThreads.Count;t.Start();
To display thread information:
this.listBox1.Items.Clear();foreach (object o in m_newThreads){ Thread t = (Thread)o; this.listBox1.Items.Add(t.Name + ": " + t.GetHashCode());}
Notice that from each thread reference t I cannot access the physical thread ID since such a property doesn't exist on the Thread type. If I required this information I could always create a thread wrapper class that returns this information using AppDomain.GetCurrentThreadId().
This sample demonstrates this and a few other things related to the subject of process and thread identities. For example, you'll note that the process identifier accessed through Process.GetCurrentProcess().Id always returns the same process ID, whereas Process.GetCurrentProcess().GetHashCode() returns a different value for each thread. This is not because they are running in a different process but because the underlying code for GetCurrentProcess actually creates a new Process object reference based on the actual physical process:
return new Process(".", false, NativeMethods.GetCurrentProcessId(), null);
Of course, consistent with the purpose of GetHashCode() discussed in Lazy Blogger's references, this generates (you guessed it) a new hash code for the object reference.
Remember Me
Designed by NUKEATION STUDIOS