HttpWebRequest Timeout in WP7 not working with tim

2019-02-19 00:37发布

问题:

Since WP7 HttpWebRequest does not support timeout, I'm using a timer to implement the functionality. Below is an example. I call GetConnection() from a UI form. But ReadCallback() is never executed till the timer time is over. Once the timer is stopped, then ReadCallBack() is triggered. Seems like the timer thread is blocking the HTTP response. Any help is appreciated. I've also tried ManualResetEvent and that has the same result too.

private HttpWebRequest conn;
private bool _timedOut = false;
private DispatcherTimer tmr;

public void GetConnection()
{
    conn = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.contoso.com"));
    conn.Method = "GET";

    tmr = new DispatcherTimer();
    tmr.Interval = TimeSpan.FromSeconds(10);
    tmr.Tick += new EventHandler(tmr_Tick);
    _stopTimer = false;

    IAsyncResult resp = conn.BeginGetResponse(new AsyncCallback(ReadCallback), conn);

    tmr.Start();
}

private void tmr_Tick(object sender, EventArgs e)
{
   if (!_stopTimer)
   {
       tmr.Stop();
       conn.Abort();
   }
}

private void ReadCallback(IAsyncResult asynchronousResult)
{
    _stopTimer = true;
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    m_response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
}

回答1:

Your code works as expected for me. When you call Abort() on a pending request, your ReadCallback is expected to fire. Then when you call EndGetResponse() you should get a WebException with Status=RequestCanceled.

Try this slightly modified code to see this in action:

private void ReadCallback(IAsyncResult asynchronousResult)
{
    _stopTimer = true;
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

    try
    {
        var m_response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
        System.Diagnostics.Debug.WriteLine("Success");
    }
    catch (WebException exc)
    {
        System.Diagnostics.Debug.WriteLine(exc.Status);
    }
}

See also on MSDN: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.abort(v=VS.95).aspx

"The Abort method cancels a request to a resource. After a request is canceled, calling the BeginGetResponse, EndGetResponse, BeginGetRequestStream, or EndGetRequestStream method causes a WebException with the Status property set to RequestCanceled."