Потоки и возвращаемые значения - C#
Формулировка задачи:
Здравствуйте, есть функция:
Я ее вызываю таким образом
Как вернуть значения ip, country_name, city в основной поток?
Как дождаться завершения этого потока?
Заранее благодарен.
public void get_geo_information(string ip, string country_name, string city)
{
string api_url = "http://freegeoip.net/json/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(api_url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream response_stream = response.GetResponseStream();
StreamReader reader_stream = new StreamReader(response_stream, System.Text.Encoding.GetEncoding("utf-8"));
string json = reader_stream.ReadToEnd();
reader_stream.Close();
var j = JObject.Parse(json);
ip = (string)j["ip"];
country_name = (string)j["country_name"];
city = (string)j["city"];
}Thread get_geo_information_thread = new Thread(() => get_geo_information(ip, country_name, city));
get_geo_information_thread.Start();Решение задачи: «Потоки и возвращаемые значения»
textual
Листинг программы
class Program
{
static void Main(string[] args)
{
GeoInfo gi = GetGeoInfoAsync().Result;
Console.WriteLine(gi);
Console.ReadKey();
}
//async method
static async Task<GeoInfo> GetGeoInfoAsync()
{
return await Task<GeoInfo>.Factory.StartNew(() => GetGeoInfo());
}
//sync method
static GeoInfo GetGeoInfo()
{
string api_url = "http://freegeoip.net/json/";
string jsonAns;
using (WebClient wc = new WebClient())
{
jsonAns = wc.DownloadString(api_url);
}
var json = JObject.Parse(jsonAns);
var gi = new GeoInfo
{
Ip = (string)json["ip"],
Country = (string)json["country_name"],
City = (string)json["city"]
};
return gi;
}
}
class GeoInfo
{
public string Ip { get; set; }
public string Country { get; set; }
public string City { get; set; }
public override string ToString()
{
return string.Format(@"IP = ""{0}""; Country = ""{1}""; City = ""{2}""", Ip, Country, City);
}
}