Search code examples
c#.nettimeout

Artificially create a connection timeout error in C#?


I want to call an external API in my application and after calling the API if a timeout exception throws then my app returns a result. Now I want to simulate this situation. This is my code :

 public string Sample()
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response =
                    client.GetAsync("ExternalApi").GetAwaiter().GetResult();
                //...
            }
        }
        catch (Exception e)
        {
            return ((HttpRequestException) e).StatusCode == HttpStatusCode.RequestTimeout ? "timeOut" : "Error";
        }

        return "Success";
    }

If I throw a TimeoutException in ExternalApi then in Sample method I get Internal server error. How to create an artificial timeout exception?


Solution

  • For this purpose, I finally use an application called 'Hercules Setup Utility'. This application listens to a port in 'Tcp Server' and get your request but doesn't respond at all. After executing this app and listening to a port, you have to set something like localhost:port in your app. You will get a timeout exception.