Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Response.WriteAsync and returning a string

Hi I was wandering if someone can explain to me the difference between these two methods for returning data from a controller. Is there an advantage or reason for using on method over the other?

I am guessing that the returning function just calls Response.WriteAsync further down the line but I am not sure.

Using postman both methods return the exact same response, so I was just curious about the two options, is there a reason for using one over the other or just personal preference.

Between 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" }));
}

and just returning:

[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" }));
}
like image 603
Heinrich Avatar asked Mar 18 '17 08:03

Heinrich


1 Answers

Basically there is a difference regarding how your code is executed under the hood. In the first case, in which you have this

await HttpContext.Response
                 .WriteAsync(JsonConvert.SerializeObject(new 
                  { 
                      data = "my_fetched_data" 
                  }));

an ASP.NET thread would be used to execute your code.

While in the second case, in which you have this

return await Task.Factory
                 .StartNew(()=>JsonConvert.SerializeObject(new 
                 { 
                     data = "my_fetched_data" 
                 }));

a thread pool thread would be used.

As it is stated 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.

That being said, I would opt for the first solution.

like image 129
Christos Avatar answered Sep 22 '22 14:09

Christos