By defualt Web Client, Http Client and Web Request classes has timeout property set to 100 seconds. And while calling our Azure function which was taking more than 100 seconds to return the reponse which is why we started getting The operation has timed out error.
To fix this issue we need to increase the timeout from by default value which is 100 seconds to appropriate time.
I will provide code to modify the timeout property for all three classes. I have modified the code to change timeout property from 100 seconds to 120 seconds and after settings this property the issue resolved and error stopped.
HttpClient
using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 2, 0);// TimeSpan.FromMinutes(2); using (HttpResponseMessage response = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result) using (HttpContent respContent = response.Content) { //HttpResponseMessage response = client.GetAsync(url).Result; Console.WriteLine("Number of calls made: " + i); Console.WriteLine(response.IsSuccessStatusCode); StreamReader responseReader = new StreamReader(respContent.ReadAsStreamAsync().Result); Console.WriteLine(responseReader.ReadToEnd()); } }
WebClient
Web client does not direct property to set timeout and we will have to use custom class which we inherit from Webclient class to use timeout property.
public class MyWebClient : System.Net.WebClient { public int Timeout { get; set; } protected override WebRequest GetWebRequest(Uri uri) { WebRequest lWebRequest = base.GetWebRequest(uri); lWebRequest.Timeout = Timeout; ((HttpWebRequest)lWebRequest).ReadWriteTimeout = Timeout; return lWebRequest; } } using (var lWebClient = new MyWebClient()) { lWebClient.Timeout = (int)TimeSpan.FromSeconds(120).TotalMilliseconds; string response = lWebClient.DownloadString(url); Console.WriteLine(response); }
Web Request class timeout property can be set same as Http Client.
Hope this helps!
One thought on “The operation has timed out error while calling Azure function from C#”