I have a console application where the user inputs a string (a number, "1" for example), and I make a GET request according to the number entered, and return the string result of the GET.
I want to to do it in async, because in general, all I/O operations should be in async, so I basically want to do the GET, wait for the result, and return the string.
My Code:
public async Task<string> getClassName()
{
Task<string> myTask = getClassNameFromClassNamer();
// Do something here
string page = await myTask;
return page;
}
public async Task<string> getClassNameFromClassNamer() /
{
string url = "...";
using (var client = new HttpClient())
{
return await client.GetStringAsync(url);
}
}
Now, the GetStringAsync never returns, and the cmd window just closes.
I also tried with ConfigureAwait(continueOnCapturedContext: false);
, didn't work.
When I tried to use
result = httpClient.GetStringAsync("...").Result;
it worked, but I get the feeling that it is not really async..
I am Working in .NET 4.5
EDIT:
calling method:
public async Task execFeature()
{
string response = await webApi.getClassName();
IResult result = new TextResult(response);
result.display();
}
and:
public async Task startService()
{
....
await feature.execFeature();
}
and in Program.cs:
featureService.startService();
So, I have 2 questions:
What is the proper way of doing an async GET to a server? I want to do the GET, get the string result and return the string.
From what I know, every web request should be done in async, because we want the other code in the app (UI, logic) to keep running. Even though right now, I don't have any other operations running or other UI to stay responsive (console application), and I am basically just waiting for the response from the server, I feel like its good practice to do the requests in async. Does that sound correct?
Thanks!
What is the proper way of doing an async GET to a server? I want to do the GET, get the string result and return the string.
You are doing it correctly.
To fix the problem with your application exiting, you have to synchronously wait for the top level task in the main
method like this:
featureService.startService().Wait();
Take a look at this reference.
I feel like its good practice to do the requests in async. Does that sound correct?
Not really. Doing IO calls asynchronously is good in two situations: