-1

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

cahyo
  • 597
  • 2
  • 5
  • 14
  • There is little practical difference. For a description of what differences do exist, see marked duplicate. Note that in your #1 example, you are doing little more than executing the same `async` method found in #2, except wrapped in a `Task`. You could have just called the `async` lambda delegate directly and returned the result. – Peter Duniho Mar 31 '17 at 04:37

1 Answers1

0

In method 1 you are explicitly creating a Task, with all the overhead of running it, and using it to await other tasks.

Method 2 is the way to go as you aren't creating the unnecessary overhead of the extra Task.

Additionally, unless you know exactly what you are doing, do not use async void - Async/Await - Best Practices in Asynchronous Programming

Jordan S. Jones
  • 13,703
  • 5
  • 44
  • 49