I want to pause a sync method. I know I can to use:
// SAMPLE 01
Thread.Sleep(30 * 1000)
but it has a disadvantage of blocking the current thread. The alternative
// SAMPLE 02
await Task.Delay(30 * 1000)
will work only in an async method. But I need this in a sync method. We cannot do it like this
// SAMPLE 03
Task.Delay(30 * 1000).Wait()
because it can cause a deadlock (at least I think so). My final solution is
// SAMPLE 04
Task.Run(() => Task.Delay(30 * 1000)).Wait();
Finally, my question: Is this solution (SAMPLE 04) really better than the SAMPLE 01 (using Thread.Sleep)?
Bonus question: SAMPLE 03 really can do a deadlock? What if we do this:
// SAMPLE 05
Task.Delay(30 * 1000).Wait(30 * 1000)
Is this solution (SAMPLE 04) really better than the SAMPLE 01 (using Thread.Sleep)?
No. It's worse. Sample 01 is both more understandable and more efficient.
it has a disadvantage of blocking the current thread.
It is true that Thread.Sleep blocks the current thread. In an asynchronous method, that would be a disadvantage.
I need this in a sync method.
By definition, then, you want to block the current thread. That's what synchronous means.
And in fact, all your examples do block the calling thread (except 02, which is asynchronous). Wait blocks the calling thread just as much as Thread.Sleep does.
SAMPLE 03 really can do a deadlock?
No. In order to have a deadlock, you need two different things waiting for each other before they can continue. For the classical sync-over-async deadlock, your two things are:
async method whose await has captured a single-threaded context.In your example, you have a thread blocked. Let's assume there's a single-threaded context and the thread is blocked in that context. You still wouldn't have a deadlock because the Task.Delay method does not capture its context. So there won't be a deadlock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With