Does the usage of Thread.Sleep(…) warrant making the method Async in an API

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:

Capture1

I definitely like the behaviour of the latter implementation much better and you can improve it some more.

Comments welcome!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blog at WordPress.com.

Up ↑

%d bloggers like this: