0

I am trying to use this in a method call to get a string from a source

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
string responseBody = await response.Content.ReadAsStringAsync();
Console.Write(responseBody);

When used outside of a method and class, it works fine with my url, and returns the proper string I am looking for. However, when I put it in my class and method, it no longer does anything. No errors, just returns nothing.

For reference, the method I am using looks like this

public async void get(String test) {

        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(test);
        string responseBody = await response.Content.ReadAsStringAsync();
        Console.Write(responseBody);
        
    }

I am clueless why this stops working once I put it into a method.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • 1
    Don't know for sure from the information given, but it's likely that since you're not returning a Task, your calling code (that calls get("url")) is not actually waiting for the request to be completed. using `async void` is considered [bad practice](https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#async-void). – Eduardo macedo Apr 07 '22 at 20:00
  • This [presentation](https://www.youtube.com/watch?v=J0mcYVxJEl0&t=1890s) gives a pretty good explanation of the issue. – Eduardo macedo Apr 07 '22 at 20:14
  • Good information, thank you very much – Noah Leightley Apr 07 '22 at 20:45
  • 3
    You might want to read this: [Avoid async void](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void). – Theodor Zoulias Apr 07 '22 at 20:48
  • And there are more dupes – JHBonarius Apr 07 '22 at 20:52

1 Answers1

1

Make your Method returning a Task and it works

public async Task get(String test)
{
    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync(test);
    string responseBody = await response.Content.ReadAsStringAsync();
    Debug.Write(responseBody);
}

private async void btnTest_Click(object sender, EventArgs e)
{
    try
    {
        Task t = get("https://stackoverflow.com/questions/71787949/c-sharp-httpclient-get-does-not-work-when-put-in-async-method");
        IEnumerable<Task> tasks = new[] { t };
        await Task.WhenAll(tasks);
    }
    catch (Exception oException)
    {
        Debug.WriteLine(oException.ToString());
    }
}
HardWorker
  • 11
  • 1