Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6587575
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T16:56:04+00:00 2026-05-25T16:56:04+00:00

I have a JSON API which I want my application to access. So I

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T16:56:04+00:00Added an answer on May 25, 2026 at 4:56 pm

    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:

    public static void DownloadString(this Uri uri, Action<string> action)
    {
        if (uri == null) throw new ArgumentNullException("uri");
        if (action == null) throw new ArgumentNullException("action");
    
        var webclient = new WebClient();
    
        DownloadStringCompletedEventHandler handler = null;
        handler = (s, e) =>
        {
            var result = e.Result;
            webclient.DownloadStringCompleted -= handler;
            webclient.Dispose();
            action(result);
        };
    
        webclient.DownloadStringCompleted += handler;
        webclient.DownloadStringAsync(uri);
    }
    

    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:

    var uri = new Uri("http://someplace.com/books.json");
    uri.DownloadString(t =>
    {
        // Do something with the string
    });
    

    Now this can be used to create a GetBooks method. Here it is:

    public void GetBooks(Uri uri, Action<List<Books>> action)
    {
        if (action == null) throw new ArgumentNullException("action");
        uri.DownloadString(t =>
        {
            var books = ParseJSON(t);
            action(books);
        });
    }
    

    It’s used like this:

    this.GetBooks(new Uri("http://someplace.com/books.json"), books =>
    {
        // Do something with `List<Books> books`
    });
    

    That should be neat and simple.

    Now, you may wish to extend this a couple of ways.

    You could create an overload of ParseJSON that has this signature:

    void ParseJSON(string text, Action<List<Books>> action)
    

    Then you could do away with the GetBooks method altogether and just write this:

    var uri = new Uri("http://someplace.com/books.json");
    uri.DownloadString(t => ParseJSON(t, books =>
    {
        // Do something with `List<Books> books`
        // `string t` is also in scope here
    }));
    

    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:

    public static void DownloadString(
        this Uri uri,
        Action<string> action,
        Action<Exception> exception)
    {
        if (uri == null) throw new ArgumentNullException("uri");
        if (action == null) throw new ArgumentNullException("action");
    
        var webclient = (WebClient)null;
    
        Action<Action> catcher = body =>
        {
            try
            {   
                body();
            }
            catch (Exception ex)
            {
                ex.Data["uri"] = uri;
                if (exception != null)
                {
                    exception(ex);
                }
            }
            finally
            {
                if (webclient != null)
                {
                    webclient.Dispose();
                }
            }
        };
    
        var handler = (DownloadStringCompletedEventHandler)null;        
        handler = (s, e) =>
        {
            var result = (string)null;
            catcher(() =>
            {   
                result = e.Result;
                webclient.DownloadStringCompleted -= handler;
            });
            action(result);
        };
    
        catcher(() =>
        {   
            webclient = new WebClient();
            webclient.DownloadStringCompleted += handler;
            webclient.DownloadStringAsync(uri);
        });
    }
    

    You can then replace the non-error handling DownloadString extension method with:

    public static void DownloadString(this Uri uri, Action<string> action)
    {
        uri.DownloadString(action, null);
    }
    

    And then to use the error handling method you would do this:

    var uri = new Uri("http://someplace.com/books.json");
    uri.DownloadString(t => ParseJSON(t, books =>
    {
        // Do something with `List<Books> books`
    }), ex =>
    {
        // Do something with `Exception ex`
    });
    

    The end result should be fairly simple to use and read. I hope this helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a web site with an API which publishes the information using JSON.
I have an application in which I am posting data to my server API
I have an existing Rails 3 application, to which I am adding a JSON
I have JSON response from Facebook, which I don't want to deserialize into a
I have following json data which I want to pass it to server using
I have an app running Rails 2.3.5 that has a JSON API for much
I have two JSON objects with the same structure and I want to concat
We have a JSON response which can contain null values (e.g. { myValue: null
I am building a Java EE web application, which also has a JAX-RS API
I want to develop an application in which i want to display restaurants nearby

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.