c# - 即使我立即获得返回任务的结果,HttpClient 是否会旋转一个新线程?

标签 c# asp.net async-await dotnet-httpclient

在我的应用程序中,我喜欢尝试保持一致并尽可能使用 HttpClient。但是,有时我不需要 HttpClient 的异步属性,所以我只是在任务返回后立即获取它的结果,如下面的代码所示。

public HttpResponseMessage httpPostWrapperMethod(string postBody, string url)
{
    HttpContent content = new StringContent(postBody, Encoding.UTF8, "application/json");

    HttpClient client = new HttpClient();

    return client.PostAsync(url, content).Result;
}

我的两部分问题是这样的:

此代码是否会导致在进行调用时在后台旋转一个新线程?

如果我对其他服务的调用大约需要 500 毫秒,当该服务处于大约 100 个请求/秒的生产负载下时,这是否会导致我消耗过多线程?

最佳答案

PostAsync 不会导致创建线程,不会。事实上,如果代码被异步使用,那么任何线程都不需要做任何事情来完成这项工作。在您的情况下,您在等待操作完成时让当前线程无所事事,因此这是执行此操作时唯一消耗/浪费时间的线程。

关于c# - 即使我立即获得返回任务的结果,HttpClient 是否会旋转一个新线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26741864/

相关文章:

c# - 列出使用 Mono.Cecil 调用方法的所有引用

c# - 嵌套类的 LINQ 查询

c# - 应该使用什么来代替 UseGoogleAuthentication 方法 (IAppBuilder)?

javascript - 找不到 JS 文件 -- 无法加载资源 : the server responded with a status of 404 ()

c# - 是什么导致 "The wait completed due to an abandoned mutex"?

c# - ASP.NET MVC : How to create an action filter to output JSON?

c# - UnmanagedMemoryStream 有什么用?

python3 - 从异步方法获取结果

node.js - 如何在for循环中正确执行异步调用?

async-await - 类型错误 : Cannot read property 'type' of undefined (redux toolkit)