gpt4 book ai didi

c# - Response.WriteAsync 和返回字符串有什么区别

转载 作者:太空狗 更新时间:2023-10-30 01:00:54 30 4
gpt4 key购买 nike

您好,如果有人可以向我解释这两种从 Controller 返回数据的方法之间的区别,我正在徘徊。使用 on 方法比其他方法有优势或理由吗?

我猜测返回的函数只是调用 Response.WriteAsync 进一步调用,但我不确定。

使用 postman 两种方法都返回完全相同的响应,所以我只是对这两个选项感到好奇,是否有理由使用一个而不是另一个,或者只是个人偏好。

在 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 和返回字符串有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42872011/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com