WP7中的HttpWebRequest超时无法与计时器一起使用 [英] HttpWebRequest Timeout in WP7 not working with timer

查看:93
本文介绍了WP7中的HttpWebRequest超时无法与计时器一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于WP7 HttpWebRequest不支持超时,因此我使用计时器来实现该功能.下面是一个例子.我从UI窗体调用GetConnection().但是直到计时器时间结束才执行ReadCallback().一旦计时器停止,便会触发ReadCallBack().似乎计时器线程正在阻止HTTP响应.任何帮助表示赞赏.我也尝试过ManualResetEvent,结果也一样.

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

推荐答案

您的代码可以正常工作.当您在待处理的请求上调用Abort()时,将触发您的ReadCallback.然后,当您调用EndGetResponse()时,应该获得一个带有Status = RequestCanceled的WebException.

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

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

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

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

这篇关于WP7中的HttpWebRequest超时无法与计时器一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆