Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement both an async method and its synchronous counterpart? [duplicate]

I have a method such as Task<string> GetContentAsync(string url) and my console application is not quite ready to take advantage of the TPL internally, but maybe at a later date it will be.

How can I easily write a synchronous wrapper (not an alternative implementation) for this (or other) methods?

like image 469
Michael J. Gray Avatar asked Nov 08 '13 18:11

Michael J. Gray


People also ask

Can synchronous methods also be asynchronous?

But some of the synchronous methods can also be asynchronous or hybrids. While direct messages and text messages can be done in real time, you may not be available to answer a colleague’s question right away.

What is the difference between synchronous and asynchronous callbacks in Java?

The problem with synchronous callbacks are that they appear to lag. An Asynchronous call does not block the program from the code execution. When the call returns from the event, the call returns back to the callback function. So in the context of Java, we have to Create a new thread and invoke the callback method inside that thread.

How to distinguish between async and non-async methods?

If you've chosen to expose both async and non-async methods, the way to distinguish between them is with the async suffix. For example, Find () and FindAsync () provides sufficient distinction. And you're already doing that. There is no reason to put them in regions or separate interfaces.

Should I go for a pure Async or async route?

I would go a pure async route because this is what you usually want and provide sync methods via extensions since they are only wrappers/decorators. I would not use #region s for this purpose.


1 Answers

If your library needs to implement both synchronous and asynchronous members, then you implement both members. There are no shortcuts (assuming this is intended to be a reusable library).

public async Task<string> GetContentAsync(string url)
{
  ... // Logic here, e.g., using HttpClient
}

public string GetContent(string url)
{
  ... // Duplicate logic here, e.g., using WebClient
}

The duplication of logic is certainly unfortunate, but if you try to take shortcuts you'll actually end up in a worse situation. The details of "why" are a bit long for an SO answer, but Stephen Toub covers the problems that arise when wrapping in his classic pair of blog posts "Should I expose synchronous wrappers for asynchronous methods?" and "Should I expose asynchronous wrappers for synchronous methods?"

BTW, the answer to both questions is "no". Also, see my SO answer here.

like image 106
Stephen Cleary Avatar answered Oct 20 '22 03:10

Stephen Cleary