C# 从PCL内的异步调用返回值
我有一个非PCL方法,它从RESTful服务获取数据,然后反序列化并返回数据。看起来像这样C# 从PCL内的异步调用返回值,c#,xamarin.forms,C#,Xamarin.forms,我有一个非PCL方法,它从RESTful服务获取数据,然后反序列化并返回数据。看起来像这样 public WeatherData GetWeather { get { if (!ftrackData.Online) return new WeatherData(); string param = string.Format("lat={0}&lon={1}&a
public WeatherData GetWeather
{
get
{
if (!ftrackData.Online)
return new WeatherData();
string param = string.Format("lat={0}&lon={1}&APPID={2}", AppDelegate.Self.Latitude, AppDelegate.Self.Longitude, AppDelegate.Self.WeatherID);
var request = WebRequest.Create("http://api.openweathermap.org/data/2.5/forecast?" + param) as HttpWebRequest;
request.Method = "GET";
request.Accept = "application/json";
request.ContentType = "application/json";
string responseContent;
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
}
}
var deserial = Deserialize<WeatherData>(responseContent);
return deserial;
}
catch (WebException ex)
{
Console.WriteLine("Deserialiser failed : {0}--{1}", ex.StackTrace, ex.Message);
return null;
}
}
}
但这不会编译,因为并非所有路径都返回值
如何才能让报税表在匿名回拨中填写好天气信息后才能返回?您不使用WebRequest.GetResponseAsync的原因是什么?您能使用.NET Framework 4.5吗?@Nodoid:通常认为在属性getter中执行异步网络调用是一种糟糕的方法。一个更好的方法是异步方法。它很简单——使用一个方法。您共享的代码中会散发出大量的代码气味-属性的代码大小应该更小,并且它不应该触及自己类之外的任何内容,尤其是网络、数据库或其他类似的内容
public WeatherData GetWeather
{
get
{
var param = string.Format("lat={0}&lon={1}&APPID={2}", App.Self.Latitude, App.Self.Longitude, App.Self.WeatherID);
var request = WebRequest.Create("http://api.openweathermap.org/data/2.5/forecast?" + param) as HttpWebRequest;
request.Method = "GET";
request.Accept = "application/json";
request.ContentType = "application/json";
var Weather = new WeatherData();
string responseContent;
try
{
var asyncResult = request.BeginGetResponse(new AsyncCallback(s =>
{
var response = (s.AsyncState as WebRequest).EndGetResponse(s);
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
}
Weather = Deserialize<WeatherData>(responseContent);
}), request);
return Weather;
}
catch (WebException ex)
{
Debug.WriteLine("Deserialiser failed : {0}--{1}", ex.StackTrace, ex.Message);
return Weather;
}
}
}
if (asyncResult.IsCompleted)
return Weather;