Here i have two different approaches to define and call async task method
1.
using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
namespace foo{
public class bar{
public bar(){
LoadData();
}
private async void LoadData(){
var data=await getData<List<string>>("http://foobar.com/city");
}
private Task<T> getData<T>(string url){
return Task.Run(async()=>{
try{
var client=new HttpClient();
var response=await client.GetAsync(url);
response.EnsureSuccessStatusCode();
using(var reader=new StreamReader(await response.Content.ReadAsStreamAsync())){
var data = JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());
return data;
}
}catch(Exception){}
return default(T);
});
}
}
}
2.
using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
namespace foo{
public class bar{
public bar(){
LoadData();
}
private async void LoadData(){
var data=await getData<List<string>>("http://foobar.com/city");
}
private async Task<T> getData<T>(string url){
try{
var client=new HttpClient();
var response=await client.GetAsync(url);
response.EnsureSuccessStatusCode();
using(var reader=new StreamReader(await response.Content.ReadAsStreamAsync())){
var data = JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());
return data;
}
}catch(Exception){}
return default(T);
}
}
}
difference of these in getData
method. 1 just using Task
and 2. using async Task
.
both of these run normally as expected, but which is the right or best approaches to use?
and please give some explanation