Dennis
Dennis

Reputation: 14475

Use async implementation of a method in its blocking version

I have created a custom subclass of Stream with an implementation of Read. The operations used in the implementation can make good use of the async API though, so I wanted to provide a ReadAsync implementation as well.

The methods share a lot of similar behaviour, and the easiest way to avoid code duplication would be to keep the logic in the ReadAsync implementation and use that in the Read implementation. This would look like this:

public override int Read(byte[] buffer, int offset, int count)
{
    return ReadAsync(buffer, offset, count).Result;
}

Would there be any implications with this approach? As the Read method should block on the current thread, I think it would perfectly fit the specification.

Thanks!

Upvotes: 1

Views: 233

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149548

Would there be any implications with this approach?

Yes, this is the sync over async anti-pattern, and it should be avoided. The main reason for that is that it can easily cause deadlocks.

How could that be? Your internal ReadAsync is probably awaiting on an asynchronous operation to be complete, while you're blocking a thread. If this thread is for example, the UI message loop thread, it's currently blocked. When your await completes (assuming you didn't use ConfigureAwait(false) internally), it would deadlock when trying to marshal back the continuations onto it.

When writing async code, you will have some amount of code duplication, there is no getting around that. Attempt to reuse as much as you can. for example, if both code methods have a synchronous part at the beginning, you can extract that to a third method which both async and sync versions will consume.

Upvotes: 6

Miroslav Nedyalkov
Miroslav Nedyalkov

Reputation: 1131

It depends on the implementation of your Async method - if it waits the current thread for something a deadlock will appear. Generally it is preferred to not block to wait for async methods.

Upvotes: 1

Related Questions