Using Task.wait() application hangs and never returns

后端 未结 2 1621
庸人自扰
庸人自扰 2021-01-11 15:36

I am new to C# and using Task. I was trying to run this application but my application hangs every time. When I am adding task.wait(), it keeps wai

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-11 16:04

    I don't understand why you use DownloadStringCompleted event and try to make it blocking. If you want to wait the result, just use blocking call 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";
    }
    

    If you want to make it async

    var location = await RetrieveFormatedAddressAsync(51.962146, 7.602304);
    
    async Task RetrieveFormatedAddressAsync(double lat,double lon)
    {
        using(HttpClient client = new HttpClient())
        {
            string xml =  await client.GetStringAsync(String.Format(baseUri,lat,lon));
            return ParseXml(xml);
        }
    }
    

提交回复
热议问题