Search code examples
c#webclientnancy

WebClient taking 43 seconds to download this json string https://jsonplaceholder.typicode.com/posts


12 hours ago (around dinner time here in Texas), it was working just fine at a moment when I hope the latency to be very high because of the high traffic.

Any idea why this could be happening and how to troubleshoot this issue?

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Nancy.Json;

namespace Training.Threading
{
    class TasksDemo
    {
        static async Task Main(string[] args)
        {
            Post[] posts = await GetPostsAsync();

            foreach(Post post in posts)
                System.Console.WriteLine(post.Title);
        }

        public static Task<Post[]> GetPostsAsync() => Task.Run(() =>
         {
             var json = new WebClient().DownloadString("https://jsonplaceholder.typicode.com/posts");
             JavaScriptSerializer ser = new JavaScriptSerializer();
             var posts = ser.Deserialize<Post[]>(json);
             return posts;
         });
    }
    public class Post
    {
        public int UserId { get; set; }
        public string Title { get; set; }
        public string Body { get; set; }
    }
}

Solution

  • I don't think the code is the issue here. It is more so your ISP or the bandwith available to the server / traffic you are trying to contact.

    Some tools that will help you diagnose the issue specifically in windows to spot your issue include

    • 'tracert' (trace route)
    • 'ping' (ping)

    In Windows:

    ping jasonplaceholder.typicode.com 
    

    To view latency between "hops"

    tracert jsonplaceholder.typicode.com
    

    this will provide in milliseconds the latency to the server you are trying to reach assuming they respond to ping request ICMP.