异步等待调用后的Console.WriteLine. [英] Console.WriteLine after async await call.

查看:182
本文介绍了异步等待调用后的Console.WriteLine.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用异步呼叫和等待完全陌生.我具有以下单元测试功能:

I'm completely new to using async calls and await. I have the below unit test function:

    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 打印语句出现在输出中-我不确定为什么.我一直在环顾四周,听起来好像我可能需要将其设置为任务?有人可以指出我正确的方向吗?

The test completes without error, but I never see the Console.WriteLine print statement show up in output - I'm not sure why. I've been looking around and it sounds like I may need to set this up as a task? Could someone point me in the proper direction?

推荐答案

由于您已经在等待HttpResponseMessage,因此一种简单(且一致)的解决方案是返回Task<HttpResponseMessage>.

Since you are already awaiting an HttpResponseMessage, a simple (and consistent) solution is to 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;
    }
}

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

That said, you also need to ensure that your test setup is correct. You cannot properly call an async method from a synchronous test. Instead, mark your test async as well and await the method you are calling. Furthermore, your test method must be marked as async Task as well since neither MS Test Runner nor other tools (NCrunch, NUnit) will properly deal with an async void test method:

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

这篇关于异步等待调用后的Console.WriteLine.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆