使用Task.wait()应用程序挂起并永远不会返回 [英] Using Task.wait() application hangs and never returns

查看:328
本文介绍了使用Task.wait()应用程序挂起并永远不会返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,使用 Task 。我试图运行这个应用程序,但我的应用程序每次都挂起。当我添加 task.wait()时,它会一直等待,永远不会返回。任何帮助深表感谢。
编辑:
我想异步调用DownloadString。当我按照Austin Salonen的建议做task.Start()时,我没有得到位置的地址,但是从returnVal得到位置字符串的默认值。这意味着在任务完成之前,位置获得了赋值。我怎样才能确保任务完成后,只有位置得到分配returnVal。

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 waiting and never returns. Any help is much appreciated. I want to call DownloadString Asynchronously. And when I am doing task.Start() as suggested by "Austin Salonen" I don't get the address of location but default value in location string from returnVal. It means that location got value assigned before task got completed. How can I make sure that after task is completed only then location gets assigned 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");
                    }
                }
            }


推荐答案

我不明白你为什么使用 DownloadStringCompleted 事件并尝试使其阻塞。如果您想等待结果,只需使用阻止呼叫 DownloadString

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";
}

如果您想使其成为异步

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);
    }
}

这篇关于使用Task.wait()应用程序挂起并永远不会返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆