IsRunning

In quite a lot of code I see following check for whether thread is running or not:

public bool IsRunning {
get {
return (this.Thread != null)
&& (this.Thread.ThreadState == ThreadState.Running);
}
}

This code has big chance of working except in one quite often used case - if you have Sleep() inside of your code. Once that enters your main thread loop, you cannot count on your thread being in Running state all of the time. And Sleep() might not even be in your code (e.g. it might be in some external library).

Better check would be:

public bool IsRunning {
get {
return (this.Thread != null)
&& ((this.Thread.ThreadState == ThreadState.Running)
|| (this.Thread.ThreadState == ThreadState.WaitSleepJoin));
}
}

P.S. If you like to mess with IsBackground thread property, also check for ThreadState.Background.

Leave a Reply

Your email address will not be published. Required fields are marked *