我是C#的新手并使用Task.我试图运行这个应用程序但我的应用程序每次都挂起.当我添加task.wait()时,它会一直等待,永远不会返回.任何帮助深表感谢.
编辑:
我想异步调用DownloadString.当我按照“Austin Salonen”的建议执行task.Start()时,我没有获取位置的地址,而是从returnVal获取位置字符串中的默认值.这意味着在任务完成之前,位置得到了值.如何确保在任务完成后只有位置被指定returnVal.
编辑:
我想异步调用DownloadString.当我按照“Austin Salonen”的建议执行task.Start()时,我没有获取位置的地址,而是从returnVal获取位置字符串中的默认值.这意味着在任务完成之前,位置得到了值.如何确保在任务完成后只有位置被指定returnVal.
public class ReverseGeoCoding { static string baseUri = "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false"; string location = "default"; static string returnVal = "defaultRet"; string latitude = "51.962146"; string longitude = "7.602304"; public string getLocation() { Task task = new Task(() => RetrieveFormatedAddress(latitude,longitude)); //var result = Task.Factory.StartNew(RetrieveFormatedAddress("51.962146","7.602304")); task.Wait(); //RetrieveFormatedAddress("51.962146","7.602304"); location = returnVal; return location; } public static void RetrieveFormatedAddress(string lat,string lng) { string requestUri = string.Format(baseUri,lat,lng); using (WebClient wc = new WebClient()) { wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); wc.DownloadStringAsync(new Uri(requestUri)); } } static void wc_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e) { var xmlElm = XElement.Parse(e.Result); var status = (from elm in xmlElm.Descendants() where elm.Name == "status" select elm).FirstOrDefault(); if (status.Value.ToLower() == "ok") { var res = (from elm in xmlElm.Descendants() where elm.Name == "formatted_address" select elm).FirstOrDefault(); //Console.WriteLine(res.Value); returnVal = res.Value; } else { returnVal = "No Address Found"; //Console.WriteLine("No Address Found"); } } }
解决方法
我不明白为什么你使用DownloadStringCompleted事件并尝试阻止它.如果要等待结果,只需使用阻塞调用DownloadString
var location = RetrieveFormatedAddress(51.962146,7.602304); string RetrieveFormatedAddress(double lat,double lon) { using (WebClient client = new WebClient()) { string xml = client.DownloadString(String.Format(baseUri,lon)); return ParseXml(xml); } } private static string ParseXml(string xml) { var result = XDocument.Parse(xml) .Descendants("formatted_address") .FirstOrDefault(); if (result != null) return result.Value; else return "No Address Found"; }
如果你想让它异步
var location = await RetrieveFormatedAddressAsync(51.962146,7.602304); async Task<string> RetrieveFormatedAddressAsync(double lat,double lon) { using(HttpClient client = new HttpClient()) { string xml = await client.GetStringAsync(String.Format(baseUri,lon)); return ParseXml(xml); } }