C# WebClient Class extension with a custom Request Timeout Introducing RyadelWebClient, a free and open-source System.Net.WebClient extension class featuring a customizable constructor and [Timeout] property

Classe ASP.NET C# per il controllo e il calcolo formale del Codice Fiscale

Today I had to fix an odd timeout issue that suddenly occurred to  one of my ASP.NET web applications: when I looked at the logs, I easily figured out that the timeout was caused by a HTTP request issued by a System.Net.WebClient instance that couldn't retrieve some data from an external website which was down.

Here was the actual error raised from the WebClient:

System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond (server ip address).

And here's the code snippet that triggered it:

Needless to say, I had wrapped the call inside a try/catch block, therefore I "just" had to deal with the WebClient timeout... which sadly happens to be hard-coded to 100.000 milliseconds (!), with no way to change it (!!), as the underlying WebRequest object used to estabilish the connection is not exposed by the "wrapper" class (!!!).

Not bad, right? Luckily enough, I googled around and quickly found a neat way to handle such situation on the StackOverflow web site. As a matter of fact, I ended up writing the folllowing subclass, which I called RyadelWebClient:

As you can see by looking at the code and comparing it with the StackOverflow accepted answer, I tried to tweak the suggestion a little bit more in order to have a more versatile class: this way you can set a precise timeout either upon instancing the object or right before using a method that uses the internal WebRequest handler. While I was there, I also took the chance to lower the default Timeout value to 30 seconds, as 100 seemed way too much for me.

WARNING: the source code is being put within this post for reference only and might not be updated: in order to be sure to get the latest version, go to the RyadelWebClient's GitHub project page.

Conclusion

That's it, at least for now: I hope that this class will help other developers to fix similar issues related to the System.Net.WebClient class and its timeout flaws.

Fork me on GitHub

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.