Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 91519

Shared HttpClient and simultaneous requests

$
0
0

I'm writing a networking layer in a Xamarin.Forms PCL project. The main class uses HttpClient to execute requests. If the request is successful, a success lambda is executed, and if the request fails a failure lambda is executed.

This is a fire and forget type scenario. I'm calling my networking class from a UI thread, and expecting the real work to be done in the success lambda whenever the request finally completes. That all works great, but I've been noticing a message in the console.

WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.

I have been reading that the intended usage of HttpClient is to have 1 instance shared and used everywhere, but it appears that if I fire off 2 simultaneous requests, each using the same HttpClient instance, this message is being generated. Is the advice I'm reading necessarily true for for Mono's HttpClient? should I instead prefer an implementation along the lines of...

using(var client = new HttpClient())
{
}

Here is some pseudo code that will give you the gist of how my program is working

// 1 shared HttpClient does all the hard work
Client client = new Client(new HttpClient());

// Just making one request causes no warning, works just as intended.
public void oneCall() {
    // Fire off a non-blocking networking function
    client.request("GET", "http://example.com",
        success: (data) => {
            //Do something
        },
        failure: (data) => {
            // Failed
        });
    // Some UI code that gets called without waiting for the request to finish.
}

// Making 2 non-blocking requests in a row causes a WARNING (see above) in the console
public void twoSimultaneousCalls() {
    client.request("GET", "http://example.com",
        success: (data) => {
            //Do something
        },
        failure: (data) => {
            // Failed
        });
    client.request("GET", "http://example.com/anotherResource",
        success: (data) => {
            //Do something
        },
        failure: (data) => {
            // Failed
        });
    // Some UI code that gets called without waiting for requests to finish.
}

So is it REALLY true in the Xamarin/mobile world that using a shared HttpClient is recommended? Is it REALLY that thread safe? Should I prefer a "using" approach instead? Are there any MaxConnections or ThreadPool type settings I can adjust to support a number of simultaneous requests?

Some reading I've done


Viewing all articles
Browse latest Browse all 91519

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>