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



我是C#的新手,正在使用Task。我试图运行这个应用程序,但我的应用程序每次都挂起。当我添加task.wait()时,它一直在等待,永远不会返回。非常感谢您的帮助。编辑:我想异步调用DownloadString。当我在做任务的时候。根据"Austin Salonen"的建议,Start()我没有从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");
                    }
                }
            }

您实际上并没有运行任务。调试和检查task.TaskStatus会显示这一点。

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

尽管如果你正在阻塞,为什么要从另一个线程开始呢?

我不明白为什么要使用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);
    }
}

最新更新