2

What is the key differences between those two methods?

First method that use Task<TResult>:

public async Task GetTaskDataFromAPI()
        {
            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync("https://fakeapi/users"))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(apiResponse);
                }
            }
        }

And second method that use simple void:

public async void GetVoidDataFromAPI()
        {
            using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.GetAsync("https://fakeapi/users"))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(apiResponse);
                }
            }
        }

I can't notice the difference when I'm debugging this code. Why and when those methods should be used and what is the main differences between them?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
dimitri
  • 109
  • 6

1 Answers1

1

The difference is simple: you cannot await the async void version.

If you call this function, how do you know when it's finished to queue something after it? You can only run other code at the same time as the continuation inside your GetVoidDataFromAPI (ie during the GetAsync call).

Blindy
  • 65,249
  • 10
  • 91
  • 131