简体   繁体   中英

Async HTTPWebrequest with Timeout

Environemnt : Windows CE / .NET Compact FrameWork 3.5.

I need some guidance in

1) Implementing a Timeout functionality for an Asynchronous Web request. ThreadPool::RegisterWaitForSingleObject() is not available for .NetCf and I'm bit stuck.

2) How to determine if network itself is not avaialable? Googling didn't help.

Note : ThreadPool::RegisterWaitForSingleObject is not available for .NET Compact FrameWork.

Here is my Async implementation:

void StartRequest ()
{
    try
    {
        HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://192.78.221.11/SomeFunc/excpopulatedept");
        RqstState myRequestState = new RqstState();
        myRequestState.request = myHttpWebRequest;

        // Start the asynchronous request.
        IAsyncResult result =
                    (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);

        // Release the HttpWebResponse resource.
        myRequestState.response.Close();
    }
    catch (WebException ex)
    {
        ;
    }
    catch (Exception ex)
    {
        ;
    }
}

private void RespCallback(IAsyncResult asynchronousResult)
{
    try
    {
        //State of request is asynchronous.
        RqstState myRequestState = (RqstState)asynchronousResult.AsyncState;
        HttpWebRequest myHttpWebRequest = myRequestState.request;
        myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);

        // Read the response into a Stream object.
        Stream responseStream = myRequestState.response.GetResponseStream();
        myRequestState.streamResponse = responseStream;

        // Begin the Reading of the contents of the HTML page and print it to the console.
        IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, 1024, new AsyncCallback(ReadCallBack), myRequestState);
        return;
    }
    catch (WebException e)
    {
        Console.WriteLine("\nRespCallback Exception raised!");
        Console.WriteLine("\nMessage:{0}", e.Message);
        Console.WriteLine("\nStatus:{0}", e.Status);
    }
}

private void ReadCallBack(IAsyncResult asyncResult)
{
    try
    {
        RqstState myRequestState = (RqstState)asyncResult.AsyncState;
        Stream responseStream = myRequestState.streamResponse;
        int read = responseStream.EndRead(asyncResult);
        // Read the HTML page and then print it to the console.
        if (read > 0)
        {
            myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
            IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, 1024, new AsyncCallback(ReadCallBack), myRequestState);
            return;
        }
        else
        {
            //Console.WriteLine("\nThe contents of the Html page are : ");
            if (myRequestState.requestData.Length > 1)
            {
                string stringContent;
                stringContent = myRequestState.requestData.ToString();
                responseStream.Close();
            }
            catch (WebException e)
            {
            }
        }
    }
}

Thank you for your time.

To continue what Eric J commented on, you have myRequestState.response.Close() just before your catches. That's almost always going to throw an exception because either response will be null, or response won't be opened. This is because you are asynchronously calling BeginGetResponse and the callback you give it will likely not be called by the time the next line (response.close) is called. You'll want to fix that instead of just hiding the exceptions because you don't know why they occur.

In terms of a timeout, because you're dealing with something that doesn't inherently have a configurable timeout, you'll have to set a timer and simply close the connection at the end of the time-out. eg

HttpWebRequest myHttpWebRequest; // ADDED
Timer timer; // ADDED

private void StartRequest()
{
        myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://192.78.221.11/SomeFunc/excpopulatedept");
        RqstState myRequestState = new RqstState();
        myRequestState.request = myHttpWebRequest;

        timer = new Timer(delegate { if (!completed) myHttpWebRequest.Abort(); }, null, waitTime, Timeout.Infinite); // ADDED
        // Start the asynchronous request.
        IAsyncResult result =
                    (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}

//... 

private void ReadCallBack(IAsyncResult asyncResult)
{
    try
    {
        RqstState myRequestState = (RqstState)asyncResult.AsyncState;
        Stream responseStream = myRequestState.streamResponse;
        int read = responseStream.EndRead(asyncResult);
        // Read the HTML page and then print it to the console.
        if (read > 0)
        {
            myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
            IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, 1024, new AsyncCallback(ReadCallBack), myRequestState);
        }
        else
        {
            completed = true; // ADDED
            using(timer)  // ADDED
            {
                timer = null;
            }
            if (myRequestState.requestData.Length > 1)
            {
                string stringContent;
                stringContent = myRequestState.requestData.ToString();
                responseStream.Close();
            }
        }
    }
}

I only copy and pasted your code, so it's as likely to compile as what you originally provided, but there should be enough there you get in going in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM