异步WebRequest超时Windows Phone 7

时间:2011-03-13 08:07:11

标签: c# windows-phone-7 asynchronous httpwebrequest

我想知道在Windows Phone7上超时HttpWebRequest的“正确”方式是什么?

我一直在阅读ThreadPool.RegisterWaitForSingleObject(),但这不能用作WaitHandles在运行时抛出一个未实现的异常。

我也一直关注ManualReset事件,但A)不能正确理解它们B)不明白如何阻止调用线程是一种在Async请求上实现超时的可接受方式。

这是我现有的代码没有超时,有人可以告诉我如何添加超时吗?

public static void Get(Uri requestUri, HttpResponseReceived httpResponseReceivedCallback, ICredentials credentials, object userState, bool getResponseAsString = true, bool getResponseAsBytes = false)
                {
                    var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);

                    httpWebRequest.Method = "GET";
                    httpWebRequest.Credentials = credentials;

                    var httpClientRequestState = new JsonHttpClientRequestState(null, userState, httpResponseReceivedCallback, httpWebRequest, getResponseAsString, getResponseAsBytes);

                    httpWebRequest.BeginGetResponse(ResponseReceived, httpClientRequestState);
                }

private static void ResponseReceived(IAsyncResult asyncResult)
{
      var httpClientRequestState = asyncResult.AsyncState as JsonHttpClientRequestState;

       Debug.Assert(httpClientRequestState != null, "httpClientRequestState cannot be null. Fatal error.");

       try
       {
           var webResponse  = (HttpWebResponse)httpClientRequestState.HttpWebRequest.EndGetResponse(asyncResult);

       }
}

1 个答案:

答案 0 :(得分:2)

C#的基本异步超时模式:

public static T SafeLimex<T>(Func<T> F, int Timeout, out bool Completed)   
   {
       var iar = F.BeginInvoke(null, new object());
       if (iar.AsyncWaitHandle.WaitOne(Timeout))
       {
           Completed = true;
           return F.EndInvoke(iar);
       }
         F.EndInvoke(iar); //not calling EndInvoke will result in a memory leak
         Completed = false;
       return default(T);
   } 

不确定这是否适用于Windows Phone 7.
您可能需要查看此内容 - Exposing asynchronous features to client code: Windows Phone 7