IsRunning

 Posted by  Programming  Add comments  Tagged with:
Feb 272012
 

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>