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

时间:2016-09-15 21:09:33

标签: c# http asynchronous 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);
    } 

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

2 个答案:

答案 0 :(得分:6)

由于您已在等待HttpResponseMessage,因此简单(一致)的解决方案是返回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;
    }
}

也就是说,您还需要确保您的测试设置正确无误。您无法从同步测试中正确调用异步方法。相反,也要标记您的测试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);
}

答案 1 :(得分:1)

我认为在这里做的最好的事情是选择public async Task POSTDataHttpContent(string jsonString, string webAddress) { using (HttpClient client = new HttpClient()) { StringContent stringContent = new StringContent(jsonString); HttpResponseMessage response = await client.PostAsync( webAddress, stringContent); // Assert your response may be? } } 返回类型而不是空格。

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


            return response;
        }
    });

    Task.Wait();
    Assert.IsNotNull(Task.Result);
}

如果你真的坚持不使用任务(这不是一个好主意):

create type type_A as (
   a int,
   b text
);