0

If I execute this and run Fiddler beside it and set a breakpoint for the request in order it to timeout.. WHY does it not timeout like it should? (I use await)

If I change the code to DownloadString it does..????

class MyWebClient : WebClient
  {
    protected override WebRequest GetWebRequest(Uri address)
    {
      WebRequest request = base.GetWebRequest(address);
      request.Timeout = 10;

      return request;
    }

  }

  public class TestIt
  {
    internal static async Task DoTest()
    {
      try
      {
        WebClient client = new MyWebClient();
        string result = await client.DownloadStringTaskAsync("https://www.google.com");
        // sync version works:
        // string result = client.DownloadString("https://www.google.com");
        Debug.Print(result);
      }
      catch (Exception ex)
      {
        Debug.Print(ex.Message);
      }
      finally
      {
        Debug.Print("finally");
      }
    }


  }
dick Verweij
  • 143
  • 6
  • 1
    The async APIs of WebClient do not respect the timeout (that's a weird and dangerous design choice, but we're stuck with it now). As much as possible, you should try using HttpClient instead of WebClient. If for some reason that's not an option for you, you need to handle the timeout yourself: https://stackoverflow.com/questions/10497853/best-approach-to-timeout-using-httpwebrequest-begingetresponse – Kevin Gosse Feb 14 '19 at 10:15
  • The idiotic thing is that the call stays in limbo for indefinite time.. exception and finally is never reached! :-( – dick Verweij Feb 14 '19 at 10:47

1 Answers1

0

From the docs:

The Timeout property affects only synchronous requests made with the GetResponse method. To time out asynchronous requests, use the Abort method.

As Kevin mentioned, for modern asynchronous code, HttpClient is usually a better choice. HttpClient was designed from the ground up with async in mind.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810