具有超时的异步HTTPWebrequest

时间:2012-10-02 17:25:34

标签: c# .net-3.5 windows-ce

Environemnt:Windows CE / .NET Compact FrameWork 3.5。

我需要一些指导

1)为异步Web请求实现超时功能。    ThreadPool :: RegisterWaitForSingleObject()不适用于.NetCf,我有点卡住了。

2)如何确定网络本身是否不可用? 谷歌搜索没有帮助。

注意:ThreadPool :: RegisterWaitForSingleObject不适用于.NET Compact FrameWork。

这是我的异步实现:

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)
            {
            }
        }
    }
}

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

为了继续Eric J评论的内容,您在捕获之前就已经myRequestState.response.Close()了。这几乎总是会抛出异常,因为response将为空,或者response将不会被打开。这是因为您异步调用BeginGetResponse,并且在调用下一行(response.close)时可能不会调用您提供的回调。你需要修复它,而不是仅仅隐藏异常,因为你不知道它们为什么会发生。

就超时而言,由于您正在处理本身不具有可配置超时的内容,因此您必须设置计时器并在超时结束时关闭连接。 e.g。

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;

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

//... 

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
            timer.Dispose();  // ADDED
            if (myRequestState.requestData.Length > 1)
            {
                string stringContent;
                stringContent = myRequestState.requestData.ToString();
                responseStream.Close();
            }
        }
    }
}

我只复制并粘贴你的代码,所以它很可能像你原来提供的那样进行编译,但是你应该有足够的进展方向。