Say you are developing an API where you have to use Thread.Sleep(…) since you are working with some device via a COM and you need to wait for the predefined amount of time before you can read from the device and there is no way around it. For example:
Rule in designing APIs in my head, is that you shouldn’t make something Async unless the underlying API(s) you are working with is also Async or uses BeginX EndX, continuations, i.e. something that is already asynchronous. By prematurely making something Async you are making an implementation decision for the consumer of the code. The code provided above doesn’t expose any such API.
However, the analogue to Thread.Sleep(…) in Async world is Task.Delay(…). While Thread.Sleep(…) actually blocks the current thread, Task.Delay(…) uses timers to achieve the same logical result.
But what if we were to think of using Task.Delay(…) as a replacement for Thread.Sleep(…). Task.Delay(…) is an Async API; so the method, following “my” rule, would also have to be Async.
Since the method would be stuck waiting for the results 99.99% of the time, the better implementation would be:
I definitely like the behaviour of the latter implementation much better and you can improve it some more.