WP7 中的 HttpWebRequest 超时不适用于计时器 [英] HttpWebRequest Timeout in WP7 not working with timer

查看:24
本文介绍了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

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

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

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