Using Task.wait() application hangs and never returns

▼魔方 西西 提交于 2019-12-01 03:25:51

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<string> RetrieveFormatedAddressAsync(double lat,double lon)
{
    using(HttpClient client = new HttpClient())
    {
        string xml =  await client.GetStringAsync(String.Format(baseUri,lat,lon));
        return ParseXml(xml);
    }
}

You aren't actually running the task. Debugging and checking task.TaskStatus would show this.

// this should help
task.Start();

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

Though if you're blocking, why start another thread to begin with?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!