使用Task.wait()应用程序挂起并永不返回

时间:2013-02-22 18:20:14

标签: c# google-api task wait reverse-geocoding

我是C#的新手并使用Task。我试图运行这个应用程序但我的应用程序每次都挂起。当我添加task.wait()时,它会一直等待并且永远不会返回。任何帮助深表感谢。 编辑: 我想异步调用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");
                    }
                }
            }

2 个答案:

答案 0 :(得分:9)

您实际上并未运行该任务。调试和检查task.TaskStatus会显示此信息。

// this should help
task.Start();

// ... or this:
Task.Wait(Task.Factory.StartNew(RetrieveFormatedAddress("51.962146", "7.602304")));

虽然如果你阻止,为什么要开始另一个线程开始?

答案 1 :(得分:2)

我不明白为什么你使用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, lat, 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,lat,lon));
        return ParseXml(xml);
    }
}