1

I want to have WebApi service so I must use HttpClient or WebClient library for Client Application

HttpClient is modern and async and it my choice but I checked performance of it

Unfortunately, CRUD operations speed is much lower than WebClient library , Especially in the first call and use

I test it with simple sample with CRUD Operations (Get-Post-Put-Delete) - same result ; performance is disappointing than WebClient

WHY ???

see this picture that get 120 records from DB with HttpClient (async) and WebClient (sync)

enter image description here

this is my codes :

    // Sync - WebClient
    public static IList<Person> GetPersonList()
    {
        using (var client = new WebClient())
        {
            client.BaseAddress = @"http://localhost:9810/";
            var str = client.DownloadString("api/person/get");
            return JsonConvert.DeserializeObject<List<Person>>(str);
        }
    }


    // Async - HttpClient
    public static async Task<IList<Person>> GetPersonAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:9810/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/person/get").ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
                return await response.Content.ReadAsAsync<IList<Person>>().ConfigureAwait(false);

            return null;
        }
    }

testing method :

var s1 = new Stopwatch();
var s2 = new Stopwatch();

s1.Start();
var p = ClientPerson.GetPersonAsync().Result;
s1.Stop();

s2.Start();
var pp = ClientPerson.GetPersonList();
s2.Stop();

label1.Text = "Async : " + s1.Elapsed.TotalSeconds
 + " | Sync : " + s2.Elapsed.TotalSeconds;
Hamed F
  • 800
  • 3
  • 11
  • 23
  • 1
    Do you make the async calls first? Is there a change if you make the sync calls first? Maybe some warm up time on the server is included in the first call. – Stilgar Apr 17 '14 at 15:24
  • 2
    Likely there's some caching involved, the HttpClient could be causing much of the data to be cached and the WebClient ends up accessing cached data. – Peter Ritchie Apr 20 '14 at 03:51
  • 3
    There is a very good answer to your question: http://stackoverflow.com/a/22561368/57369 - you need to use a single instance of HttpClient for the lifetime of your application – Gabriel Oct 29 '15 at 05:51

0 Answers0