I have a JSON API which I want my application to access. So I wrote a method.
public List<Books> GetBooks()
{
var webclient = new WebClient();
var jsonOutput = webclient.DownloadString(
new Uri("http://someplace.com/books.json")
);
return ParseJSON(jsonOutput);//Some synchronous parsing method
}
Now I need to change DonwloadString to DownloadStringAsync.
I found this tutorial.
But this just seems too complicated. I’m trying to get this working, but am not sure if this is the right way to go. Perhaps there is a simpler and better way?
All of the async operations that require you to subscribe to events to get the results are just painful. I think that the simplest way to go is to abstract away the event handling into some nice extension methods and use continuation passing style (CPS) to process the results.
So, the first thing is to create an extension method for downloading strings:
This method hides away the creation of the
WebClient, all of the event handling, and the disposing and unsubscribing to clean things up afterwards.It’s used like this:
Now this can be used to create a
GetBooksmethod. Here it is:It’s used like this:
That should be neat and simple.
Now, you may wish to extend this a couple of ways.
You could create an overload of
ParseJSONthat has this signature:Then you could do away with the
GetBooksmethod altogether and just write this:Now you have a nice neat fluent-style, composable set of operations. As a bonus the downloaded string,
t, is also in scope so you can easily log it or do some other processing if need be.You may also need to handle exceptions and these can be added like so:
You can then replace the non-error handling
DownloadStringextension method with:And then to use the error handling method you would do this:
The end result should be fairly simple to use and read. I hope this helps.