14

I am using to check the condition of a thread with if(Thread.IsAlive). A form is running in this thread. At times during execution, even though the form remains open, the call to Thread.IsAlive seems to be evaluating to false. I thought to perform the same check with if(Thread.ThreadState==ThreadState.Running). Is it the right way to do? If not, what is the possible work around?

Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97
  • @daveL : even i hate it when i say it seems to behave like this. But the problem is that I can see the form that is running on that thread on my desktop, yet thread.isalive code is not getting executed. – Victor Mukherjee Apr 26 '13 at 13:07
  • 1
    Seems like @daveL has a hard time dealing with ambiguity, at least it seems that way... :p – kingdango Nov 22 '13 at 15:00

1 Answers1

18

msdn Thread.IsAlive Property true if this thread has been started and has not terminated normally or aborted; otherwise, false.

msdn Thread.ThreadState

  • Running
    The thread has been started, it is not blocked, and there is no pending ThreadAbortException.
  • StopRequested
  • SuspendRequested
  • Background
  • Unstarted
  • WaitSleepJoin
  • Suspended
  • AbortRequested

I think now it's clear Running is not the same as IsAlive

Community
  • 1
  • 1
WhileTrueSleep
  • 1,524
  • 1
  • 19
  • 32
  • 7
    IsAlive is mostly useful when you're starting a thread. if(!thread.IsAlive) thread.Start(); It's not a safe way to see if a thread is RUNNING because there are many states between NOT STARTED and STARTED that aren't equal to RUNNING. IsAlive really just tells you not to try to start it again. – kingdango Nov 22 '13 at 15:02
  • 3
    Is it a safe way to periodically check to make sure the thread has not exited ? – Bill Greer Mar 07 '15 at 14:09
  • Suspended no longer appears to be a valid threadstate. Can anyone recommend an alternative? – user2924019 Nov 01 '17 at 13:24