C# 异步操作未完成
我有个问题。我的代码没有返回用于分配全局变量的纬度和经度 调试时,我注意到这一行:C# 异步操作未完成,c#,json,parsing,windows-phone-7,C#,Json,Parsing,Windows Phone 7,我有个问题。我的代码没有返回用于分配全局变量的纬度和经度 调试时,我注意到这一行: webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted); 我注意到这一行不起作用,调试器似乎越界了,最终没有得到我需要的方法,不知道为什么会发生这种情况,早些时候它工作正常 private void GetDestination()
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
我注意到这一行不起作用,调试器似乎越界了,最终没有得到我需要的方法,不知道为什么会发生这种情况,早些时候它工作正常
private void GetDestination()
{
if (txtSearchTo.Text != String.Empty)
{
string url = String.Format("http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false", txtSearchTo.Text);
try
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(url));
}
catch
{
///todo: criar if para verificar conexão
MessageBox.Show("Verify your connection and try again!");
}
}
else
{
txtSearchTo.Focus();
}
}
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("Verify your connection and try again!");
}
else
{
// Save the feed into the State property in case the application is tombstoned.
this.State["json"] = e.Result;
destination = ParserJSON(e.Result);
}
}
private GeoCoordinate ParserJSON(string pJSON)
{
//Se o JSON está presente
if (pJSON != null)
{
try
{
//Faz a conversão (parse) para um tipo jObject
JObject jObj = JObject.Parse(pJSON);
//Le o objeto da lista inteira
JArray results = jObj["results"] as JArray;
JToken firstResult = results.First;
JToken location = firstResult["geometry"]["location"];
GeoCoordinate coord = new GeoCoordinate()
{
Latitude = Convert.ToDouble(location["lat"].ToString()),
Longitude = Convert.ToDouble(location["lng"].ToString())
};
return coord;
}
catch
{
///todo: if para verificar conexão
MessageBox.Show("Verify your connection and try again!");
}
}
return null;
}
我听说API中的某些内容可能会限制我,但我在那里检查了Url和JSon,您可以看到代码生成的带有JSon的Url。如何处理全局变量?@hatchet我使用它来获取设备所在位置坐标的距离(以米为单位)。函数是GetDistanceTo(),但我认为这不会影响,对吗?可能是在请求执行时,您在某个地方阻塞了UI线程?您在完成的事件上得到了什么吗?@KooKiz可能是因为我的变量为零。我有一个进步,但仍然有一些错误。我了解了一些异步方法的概念,可以解决很多问题,但仍然没有一个完整的解决方案。