Using Task.wait() application hangs and never returns

后端 未结 2 1622
庸人自扰
庸人自扰 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:00

    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?

    0 讨论(0)
  • 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<string> RetrieveFormatedAddressAsync(double lat,double lon)
    {
        using(HttpClient client = new HttpClient())
        {
            string xml =  await client.GetStringAsync(String.Format(baseUri,lat,lon));
            return ParseXml(xml);
        }
    }
    
    0 讨论(0)
提交回复
热议问题