3

I'm trying to get a .NET thread state.
For this I check the ProcessThread.ThreadState property.
However when I use Thread.Sleep on that thread and check its state with Process Explorer - I see that it's in "Wait: Delay Exectuion", while my ThreadState is still "Running".
How can that be?

Idov
  • 5,006
  • 17
  • 69
  • 106
  • 3
    Can you try calling `Refresh` on the `Process` object before accessing `ThreadState`? – Mike Zboray Jan 02 '13 at 09:04
  • Are you doing this for debugging purposes? [`ThreadState`](http://msdn.microsoft.com/en-us/library/system.threading.thread.threadstate.aspx): "Thread state is only of interest in debugging scenarios. Your code should never use thread state to synchronize the activities of threads." – Damien_The_Unbeliever Jan 02 '13 at 09:15
  • @mikez: I did call "Refresh" on that process, but I kept a copy of that ProcessThread and looked at it instead of the new one, because I thought it will be refreshed too. If you post this as an answer, I will accept it. thanks :) – Idov Jan 02 '13 at 09:29
  • The .NET ThreadState doesn't have anything to do with the operating system's thread state. Sleep() is just a plain method as far as .NET is concerned. – Hans Passant Jan 02 '13 at 16:50

1 Answers1

1

The Process class caches properties on first access, so you will probably need to call the Refresh method to get an updated ThreadState. It seems that the ProcessThread objects (from the ProcessThreads property) are not attached to the parent Process, and the values it contains are not updated when Refresh is called. You will need to go through the Process object again.

Something like:

Process p = Process.GetProcessByName("MyProcess);

while(true)
{
  p.Refresh();
  Console.WriteLine(p.ProcessThreads[0].ThreadState);
  Thread.Sleep(1000);
}
Mike Zboray
  • 39,828
  • 3
  • 90
  • 122