Freigeben über


SYSK 224: Why Join Is Better Than Sleep

All the “best practices” I’ve seen recommend avoid calling System.Thread.CurrentThread.Sleep() method. Agreed; but there are some legitimate situations when you just have to block for a certain period of time… If that is the case, consider using System.Thread.CurrentThread.Join() instead – just like Sleep, it will blocks the calling thread until a thread terminates or the specified time elapses, but it will continue to perform standard COM and SendMessage pumping

Comments

  • Anonymous
    October 23, 2006
    There's legitimate uses for Sleep(0). But, outside of debugging using Sleep(value>0) means the thread is blocked for a specific amount of time.  If it's a background thread (i.e. Thread.IsBackground==true) then it will terminate without freeing resources when the application exits while in Sleep() (the reason why Thread.Suspend and Thread.Resume are now obsolete).  If it isn't a background thread the application will hang on exit until that thread is done sleeping.  And that's just two examples of why Sleep(x>0) is bad design.  There's lots of other blogs on the subject. There's also lots of blog entries about alternatives to Sleep(x>0), see http://msmvps.com/blogs/peterritchie/archive/2006/10/13/2700_System.Threading.Thread.Suspend_280029002700-is-obsolete_3A00_-2700_Thread.Suspend-has-been-deprecated_2E002E002E00.aspx for an example of creating a thread that can suspend and be resumed.  It would be trivial to change it to suspend for a specific amount of time while still being able to be terminated while "sleeping".

  • Anonymous
    October 24, 2006
    Вместо эпиграфа: information hiding (1) In programming, the process of hiding details of an object or

  • Anonymous
    December 15, 2010
    By the way it is not "System.Thread.CurrentThread.Sleep()"; it is "System.Thread.Sleep()". Sleep() is a static method