HttpWebRequest.BeginGetResponse method

Maxim Bulatov 1 Reputation point
2020-12-02T11:50:44.64+00:00

Hello.
I have carefully read the code example at https://video2.skills-academy.com/ru-ru/dotnet/api/system.net.httpwebrequest.begingetresponse?view=net-5.0#-----------
and tried to run it. It worked fine, but i wanted to test TimeoutCallback (when timedout == true) by decreasing DefaultTimeout to 500 ms. And i got 2 exceptions:

  1. after request.Abort(); starts RespCallback method and line
    myRequestState.response = (HttpWebResponse) myHttpWebRequest.EndGetResponse(asynchronousResult);
    throws exception (Status:RequestCanceled);
  2. in Main method: line
    myRequestState.response.Close();
    throws null-reference-exception (myRequestState.response is null).
    Maybe it makes sense to improve the code?
    Did I fix it optimally next way?
  3. private static void RespCallback(IAsyncResult asynchronousResult)
    {
    if (((Task<WebResponse>)asynchronousResult).Status != TaskStatus.Canceled)
    try...
  4. in Main()
    // Release the HttpWebResponse resource.
    if (myRequestState.response != null)
    myRequestState.response.Close();
    Or can you suggest a better solution?
    Thanks
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,573 questions
{count} votes