【问题标题】:HttpWebRequest Timeout in WP7WP7 中的 HttpWebRequest 超时
【发布时间】:2011-04-05 22:19:48
【问题描述】:

我正在尝试为我的 WP7 应用程序实现 HttpWebRequest 超时,因为用户可以发出请求,并且该请求将永远不会返回,在屏幕上留下一个 ProgressBar。

我看到了这个 MSDN 页面:msdn page

什么用途

ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);

我能够添加此代码,并将所有变量链接起来,但是当我将它添加到我的代码中时,它会在到达该行时给出 NotSupportedOperation

allDone.WaitOne();

如果我将其注释掉,它会在我的下一行给出相同的 NotSupportedOperation

return _result_object;(函数为private object SendBeginRequest()

如何在 WP7 中添加超时?这种方式似乎行不通。由于 UI 线程问题,我不想使用 WebClient。

【问题讨论】:

    标签: c# windows-phone-7


    【解决方案1】:

    如果您错过了它,allDone 应该是 ManualResetEvent,您可以传递整数毫秒或 TimeSpan 作为在继续之前等待的时间量。例如:

    private ManualResetEvent _waitHandle = new ManualResetEvent(false);
    private bool _timedOut;
    
    ...
        this._timedOut = false;
        this._waitHandle.Reset();
        HttpWebRequest request = HttpWebRequest.CreateHttp("http://cloudstore.blogspot.com");
        request.BeginGetResponse(this.GetResponse_Complete, request);
    
        bool signalled = this._waitHandle.WaitOne(5);
        if (false == signalled)
        {
            // Handle the timed out scenario.
            this._timedOut = true;
        }
    
        private void GetResponse_Complete(IAsyncResult result)
        {
            // Process the response if we didn't time out.
            if (false == this._timedOut)
            {
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                WebResponse response = request.EndGetResponse(result);
    
                // Handle response. 
             }
         }

    或者,您可以使用第三方库,例如 Hammock,它使您可以进行超时和重试(除其他外)。不过,根据您的项目,这可能超出您的需要:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-14
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 2015-01-28
      相关资源
      最近更新 更多