异步等待调用后的Console.WriteLine.

Rok*_*545 6 c# asynchronous http httpclient

我完全不习惯使用异步调用和等待.我有以下单元测试功能:

    public async static void POSTDataHttpContent(string jsonString, string webAddress)
    {
        HttpClient client = new HttpClient();
        StringContent stringContent = new StringContent(jsonString);
        HttpResponseMessage response = await client.PostAsync(
            webAddress,
            stringContent);

        Console.WriteLine("response is: " + response);
    } 
Run Code Online (Sandbox Code Playgroud)

测试完成没有错误,但我从未看到Console.WriteLine打印语句显示在输出中 - 我不知道为什么.我一直在环顾四周,听起来我可能需要将其设置为一项任务?有人能指出我正确的方向吗?

Dav*_*d L 6

既然您已经在等待HttpResponseMessage,那么一个简单(且一致)的解决方案就是return Task<HttpResponseMessage>

var x = await POSTDataHttpContent("test", "http://api/");

public async Task<HttpResponseMessage> POSTDataHttpContent(
    string jsonString, string webAddress)
{
    using (HttpClient client = new HttpClient())
    {
        StringContent stringContent = new StringContent(jsonString);
        HttpResponseMessage response = await client.PostAsync(
        webAddress,
        stringContent);

        Console.WriteLine("response is: " + response);

        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

也就是说,您还需要确保测试设置正确。您无法从同步测试中正确调用异步方法。相反,async还要标记您的测试并等待您要调用的方法。此外,还必须标记您的测试方法async Task,因为MS Test Runner和其他工具(NCrunch,NUnit)都不会正确处理异步void测试方法:

[TestMethod]
public async Task TestAsyncHttpCall()
{
    var x = await POSTDataHttpContent("test", "http://api/");
    Assert.IsTrue(x.IsSuccessStatusCode);
}
Run Code Online (Sandbox Code Playgroud)