This article analyzes the difference between sleep and wait in C# in more detail. Share it for your reference. The specific analysis is as follows:
sleep and wait are both ways to temporarily stop execution of threads, but they are very different.
①. sleep is a method of thread class Thread. It makes the current thread temporarily sleep and can be placed anywhere.
wait is a method of the Object class. It makes the current thread temporarily give up the use of the object and wait, and must be placed in the synchronization method or synchronization block.
②. When using Sleep, the thread will not give up the right to use the object, that is, it will not release the object lock. Therefore, when using sleep in the synchronization method or synchronization block, when one thread accesses, other threads will also be inaccessible.
Wait will release the object lock, which means that the current thread gives up the use of the object and allows other threads to access it.
③. When a thread executes the wait method, another thread needs to call notify to wake up.
Sleep only temporarily sleeps for a certain period of time. After the time is up, it will automatically resume operation without requiring another thread to wake up.
I hope this article will be helpful to everyone's C# programming.