Return HTTP response immediately to ASP.NET Web API

I am working on a WebAPI2 project doing some data collection, and I'm trying to figure out how to reduce the response time of my API methods.

I have a JavaScript function that sends information to my api. My API receives this information, inserts it into the database, and then returns HTTP Accepted.

Suppose data processing time of 5 seconds is completed

// POST api/<controller>
public HttpResponseMessage Post([FromBody]string value)
{
  //This represents 5000 milliseconds of work
  System.Threading.Thread.Sleep(5000);

  return new HttpResponseMessage(HttpStatusCode.Accepted);

}

This means that when my JavaScript function calls the Post method, it expects 5 seconds of response.

Can I immediately return an HTTP Accepted response, and then continue processing my data?

Update solution from lilo.jacob

Ok, I updated my method with the threading solution that was found below. Here is the new code

// POST api/<controller>
public HttpResponseMessage Post([FromBody]string value)
{
  new System.Threading.Tasks.Task(() =>
    {
      //This represents 5000 milliseconds of work
      System.Threading.Thread.Sleep(5000);
    }).Start();

  return new HttpResponseMessage(HttpStatusCode.Accepted);
}

, , . Fiddler, Response time in fiddler

WebAPI , 4,5 7, . 11 , 5- .

, .

+4
2

"" .

:

// POST api/<controller>
public HttpResponseMessage Post([FromBody]string value)
{
    new System.Threading.Tasks.Task(() =>
    {
        //insert to db code;
    }).Start();

    return new HttpResponseMessage(HttpStatusCode.OK);

}
+6

Source: https://habr.com/ru/post/1540404/


All Articles