New ASP.NET Web API HttpClient has been giving me some strange results. Here is my code:
class Program {
static async void Main(string[] args) {
var address = "http://localhost:3895/api/urls";
Console.WriteLine(await getStringAsync(address));
Console.ReadLine();
}
public static async Task<string> getStringAsync(string uri) {
var httpClient = new HttpClient();
return await httpClient.GetStringAsync(uri);
}
}
This never comes back and the console suddenly appears and disappears. When I change the code as below, it works as it is supposed to:
static void Main(string[] args) {
var address = "http://localhost:3895/api/urls";
Console.WriteLine(getString(address));
Console.ReadLine();
}
public static string getString(string uri) {
var httpClient = new HttpClient();
return httpClient.GetStringAsync(uri).Result;
}
Any idea on what would be the issue?
asynconMainis disallowed in the VS11/.NET 4.5 compiler, so I’m assuming you’re using the Async CTP. If using .NET 4.5 is at all an option, do make the switch.That aside, the reason it doesn’t work is because
async, or more generally, tasks, rely on being able to signal some way for the remainder of the code to be executed. It works with.Resultbecause the code runs synchronously, so the problem doesn’t apply.There is no built-in support for console applications, because they don’t normally use message loops in the way that for example WinForms does, but you can look at
Microsoft Visual Studio Async CTP\Samples\(C# Testing) Unit Testing\AsyncTestUtilities, notablyGeneralThreadAffineContext.cs, to get a basic example that works in console applications too.