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?
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.
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.
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.
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.
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.
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