WP7中的IAsyncResult,如何知道异步方法何时完成?

时间:2012-03-07 15:25:51

标签: .net-4.0 windows-phone-7.1

 public string MyMethod(string param1)
     {
       var url = string.Format(UrlMask, HttpUtility.UrlEncode(param1), Login, ApiKey);
       HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
       request.BeginGetResponse(result =>
                {
                    var requestInternal = (HttpWebRequest)result.AsyncState;
                    var response = (HttpWebResponse)requestInternal.EndGetResponse(result);

                    using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        var resultXml = XDocument.Load(response.GetResponseStream());
                        var x = from r in resultXml.Descendants("node")
                                select r.Element("element").Value;

                    }
                }, request);

                return null;
            }
当lambda函数完成时,

MyMethod应返回string值。我的问题是:

  • 我怎么知道lambda函数里面的时间 request.BeginGetResponse会完成吗?
  • 如何MyMethod了解它以返回值?

1 个答案:

答案 0 :(得分:1)

要查看lambda何时完成,您可以使用如下的ManualResetEvent:

    public string MyMethod(string param1) 
    {
        const int timeOutInMs = 1000;

        using (ManualResetEvent ended = new ManualResetEvent(false))
        {
            var url = string.Format(UrlMask, HttpUtility.UrlEncode(param1), Login, ApiKey);
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.BeginGetResponse(result =>
                                         {
                                             var requestInternal = (HttpWebRequest) result.AsyncState;
                                             var response = (HttpWebResponse) requestInternal.EndGetResponse(result);
                                             using (
                                                 StreamReader streamReader =
                                                     new StreamReader(response.GetResponseStream()))
                                             {
                                                 var resultXml = XDocument.Load(response.GetResponseStream());
                                                 var x = from r in resultXml.Descendants("node")
                                                         select r.Element("element").Value;
                                             }
                                             ended.Set();
                                         }, request);

            if (!ended.WaitHandle.WaitOne(timeOutInMs))
            {
                throw new TimeoutException("lambda took too long to complete");
            }
        }
        return null; 
    }