In one of my recent interviews I was asked about Sleep vs Wait. If I understand correctly then Sleep belongs to Thread and Wait is related to Task. So, I explained separately both of them not the comparison. But interviewer was not happy. He said there are couple of things can be done by both so comparison is needed to decide which is better to use in which scenario. Also, he was expecting how these two behave when lock is acquired. In short after our discussion I have got 2 basic questions:
- Can we really compare Sleep and Wait in the context of .Net? If yes then what would be the points?
- Suppose they already have acquired some lock and then we Sleep or Wait then what will happen to Lock, will it be released? (Not sure about this scenario whether it is practical or not)
The above statement might be confusing because I am confused about what he said/expecting but I tried to writ whatever we discussed. So, I would appreciate if anyone shares their knowledge on above confusing situation.
CodePudding user response:
Can we really compare Sleep and Wait in the context of .Net? If yes then what would be the points?
Yes. These are seemingly similar mechanisms but they differ significantly and are meant to be use for different purposes. Main differences are:
Task.Wait()
is called on a Task (so basically on an object) -Thread.Sleep()
is called on a specific thread.Task.Wait()
is used to await task result with set timeout. If the task does not finish within specified time span, execution is resumed and method returnsfalse
. -Thread.Sleep()
is used to freeze thread execution (to synchronize its activities with other threads). If it is interrupted, an exception is raised and if it is ignored, the thread gets stopped.- Both mechanisms can be interrupted.
Thread.Sleep()
can be awaken either byThread.Interrupt()
orThread.Abort()
-Task.Wait()
can be interrupted by Task cancellation or its exception.
Sources: