c# – Response.WriteAsync和返回字符串之间的区别是什么
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – Response.WriteAsync和返回字符串之间的区别是什么,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1801字,纯文字阅读大概需要3分钟。
内容图文
![c# – Response.WriteAsync和返回字符串之间的区别是什么](/upload/InfoBanner/zyjiaocheng/811/1751a076b6714dc2a6c3e0f451b1106b.jpg)
嗨,如果有人能向我解释这两种从控制器返回数据的方法之间的区别,我就会徘徊.
使用方法优于另一方是否有优势或理由?
我猜测返回的函数只是进一步调用Response.WriteAsync,但我不确定.
使用邮递员这两种方法都返回完全相同的响应,所以我只是对这两个选项感到好奇,是否有理由使用其中一个或仅仅是个人偏好.
在Response.WriteAsync之间:
[HttpGet("Fetch_WriteAsync")]
public async Task Fetch_AsyncWrite()
{
HttpContext.Response.ContentType = "application/json";
await HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { data = "my_fetched_data" }));
}
然后回来:
[HttpGet("Fetch_Return")]
public async Task<string> Fetch_Return()
{
HttpContext.Response.ContentType = "application/json";
return await Task.Factory.StartNew(()=>JsonConvert.SerializeObject(new { data = "my_fetched_data" }));
}
解决方法:
基本上,您的代码在引擎盖下的执行方式存在差异.在第一种情况下,你有这个
await HttpContext.Response
.WriteAsync(JsonConvert.SerializeObject(new
{
data = "my_fetched_data"
}));
ASP.NET线程将用于执行您的代码.
而在第二种情况下,你有这个
return await Task.Factory
.StartNew(()=>JsonConvert.SerializeObject(new
{
data = "my_fetched_data"
}));
将使用线程池线程.
正如here所述:
You can use the ThreadPool in exactly the same way in ASP.NET and it
works just as you would expect. The problem is not in the ThreadPool
itself but in what else ASP.NET uses it for at the same time. ASP.NET
is multi-threaded by design and it uses the ThreadPool to serve pages
and content mapped to the ASP.NET ISAPI filter.If you also use the ThreadPool, then ASP.NET has fewer threads to
utilize and requests are put on hold until the pool returns a free
thread. This might not be a problem for a low traffic site, but more
popular sites can get into trouble. Low traffic sites can get into
trouble if they use the ThreadPool a lot.
话虽这么说,我会选择第一个解决方案.
内容总结
以上是互联网集市为您收集整理的c# – Response.WriteAsync和返回字符串之间的区别是什么全部内容,希望文章能够帮你解决c# – Response.WriteAsync和返回字符串之间的区别是什么所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。