none
一个方法的同步与异步的问题?急需返回值 RRS feed

  • 问题

  •  /// <summary>
        /// 传经纬度得到地址
        /// </summary>
        /// <param name="longitude">经度</param>
        /// <param name="latitude">纬度</param>
        /// <returns>详细地址</returns>
        public string GetAddressByGPS(double longitude, double latitude, object vehicleInfo)
        {
          int iLng = (int)(longitude * 100000);
          int iLat = (int)(latitude * 100000);
    
          WebRequest request = WebRequest.Create(Config.BMSSettings.LingTuGPS + iLng.ToString()
                  + "," + iLat.ToString() + "&t=" + m_rand.Next());
          request.Method = "get";
          request.ContentType = "application/x-www-form-urlencoded";
          request.Timeout = 5000;//设置超时
          string strAddress = null;
          IAsyncResult Ias = request.BeginGetResponse((ar1) =>
            {
              try
              {
                WebResponse response = request.EndGetResponse(ar1);
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(936)))
                {
                  strAddress = sr.ReadToEnd();
                  XPathDocument xpathDoc = new XPathDocument(new StringReader(strAddress));
                  XPathNavigator xpathNav = xpathDoc.CreateNavigator();
                  XPathNavigator nodeCode = xpathNav.SelectSingleNode("//code");
    
                  if (nodeCode.InnerXml == "0")
                  {
                    XPathNavigator nodeMsg = xpathNav.SelectSingleNode("//msg");
                   【strAddress = nodeMsg.InnerXml;】               
                  }
                  else
                  {
                    strAddress = "无法获取地址";
    
                  }
                }
                response.Close();
                LogHelper.Writeln("In GetAddressByGPS()");
    
              }
              catch
              {
                strAddress = "无法获取地址";
                LogHelper.Writeln("In GetAddressByGPS() In Error");
    
              }
            }, null);
           return strAddress;
    }
    
    
    执行完到标注的时候,无法执行后面的return,也就调用这个方法得不到strAddress 值,请求是异步的,主方法是同步的,但是我要获取这个返回值,真的不知道怎么办了?
    
    2011年3月15日 10:50

答案

  • }, null);
    
    Ias.AsyncWaitHandle.WaitOne();
    
    return strAddress;
    

    试试在return strAddress;上面增加对异步操作的同步等待。

     



    理解的越多,需要记忆的就越少
    2011年3月16日 2:25
    版主