GOTCHA 48 The Thread classThread class


GOTCHA #48 The Thread classThread class

The THRead class provides a number of methods and properties to work with a specific thread. There are certain members in the Thread class, however, that you should not use, or use only with extreme caution. Here are some you should think twice about:

  • The IsAlive property tells you if the thread represented by the Thread instance is alive or not. The problem is that the thread may die right after you call this method, but before you make a decision based on that information.

  • The THReadState property has the same drawbacks as IsAlive.

Now let's look at some potentially dangerous methods:

  • The Suspend() method pauses, freezes, or suspends a thread of execution. But it is a blunt instrument. Any resources locked by the thread are held while it is blocked. This may easily result in a deadlock. Suspend() is not intended for normal day-to-day application programming. Do not use it, for example, to synchronize thread execution.

  • The Resume() method reactivates a suspended thread. For the same reasons mentioned above in connection with Suspend(), you should avoid it.

  • The ResetAbort() method cancels an Abort() request on a thread. This may surprise a programmer who has called Abort() and has a reasonable expectation that the thread will go away.

If you think you need any of the methods mentioned above, you should revisit your design (For good discussions of multithreading issues, refer to [Lea00].) The most effective way to communicate between threads is to use what I call bait. Set some fields to a certain (boolean) value and let the other thread check for that value to take a particular action or terminate. You might also consider other facilities, such as Wait(), Pulse(), Join(), and synchronizing on a wait handle.

IN A NUTSHELL

Certain methods and properties of the THRead class have unpredictable behavior. Avoid them, or use them with extreme caution.

SEE ALSO

Gotcha #49, "Foreground threads may prevent a program from terminating," Gotcha #53, "Environment.Exit() brings down the CLR," and Gotcha #54, "ResetAbort() may lead to surprises."



    .NET Gotachas
    .NET Gotachas
    ISBN: N/A
    EAN: N/A
    Year: 2005
    Pages: 126

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net