Negin
Negin

Reputation: 169

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?

Upvotes: 1

Views: 2719

Answers (4)

Programmer
Programmer

Reputation: 75

The HttpClient class has a Timeout attribute. Or you can use some apps to create timeout like Hercules Setup Utility

Upvotes: 1

Negin
Negin

Reputation: 169

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.

Upvotes: 1

O. Jones
O. Jones

Reputation: 108766

The HttpClient class has a Timeout attribute.

So try this.

using (HttpClient client 
     = new HttpClient(){Timeout=new TimeSpan(0,5,0)})

for a five minute timeout.

If the timeout expires you'll get a WebException.

Upvotes: 2

Geckoo1337 LudumDare
Geckoo1337 LudumDare

Reputation: 11

I recently did an alternative to Tracert using a Task method so as to get an exception if something goes wrong sending a request for DNS info. I guess that you should use Task<>. Take a look at the main MSDN explanation :

https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task?view=net-5.0

Also I think that you could appreciate how I check success or exception in my own code. Take a look at the code inside the boolean DNS check :

An alternative class for Tracert with DNS feature

Upvotes: -1

Related Questions