HttpClient GetStringAsync - it never returns

The new ASP.NET HttpClient web API gave me some weird 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);
    }
}

It never returns, and the console suddenly appears and disappears. When I change the code as shown below, it works as expected:

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 what the problem is?

+5
source share
1 answer

asyncon is Mainnot allowed in the VS11 / .NET 4.5 compiler, so I assume you are using Async CTP. If using .NET 4.5 is an option, make a switch.

, , , , async , , - , . .Result, , .

, , WinForms, Microsoft Visual Studio Async CTP\Samples\(C# Testing) Unit Testing\AsyncTestUtilities, GeneralThreadAffineContext.cs, , .

+9

All Articles