HttpWebRequest WP7中的超时不能与计时器一起使用

时间:2011-04-05 15:19:31

标签: windows-phone-7 httpwebrequest timeout

由于WP7 HttpWebRequest不支持超时,我正在使用计时器来实现该功能。以下是一个例子。我从UI表单调用GetConnection()。但是,在计时器时间结束之前,ReadCallback()永远不会被执行。一旦计时器停止,则触发ReadCallBack()。似乎计时器线程正在阻止HTTP响应。任何帮助表示赞赏。我也尝试过ManualResetEvent,结果也一样。

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 个答案:

答案 0 :(得分:3)

您的代码对我有效。当您在挂起的请求上调用Abort()时,您的ReadCallback将被触发。然后当你调用EndGetResponse()时,你应该得到一个状态= RequestCanceled的WebException。

尝试使用稍微修改过的代码来查看此操作:

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

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

Abort方法取消对资源的请求。取消请求后,调用BeginGetResponse,EndGetResponse,BeginGetRequestStream或EndGetRequestStream方法会导致WebException并将Status属性设置为RequestCanceled。