문제

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

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

Lets say there is a 5 second wait time for the data processing to be 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, when my JavaScript function calls the Post Method, it waits 5 seconds for the response.

Is there a way I can immediately return a response of HTTP Accepted, and then continue processing my data?

Update solution from lilo.jacob

Ok, I've updated my method with the threading solution 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);
}

The response is returned almost immediately, which is exactly what I was looking for. Here are some results from Fiddler showing the change in response time Response time in Fiddler

The first response show the lag with WebAPI on startup, requests 4,5, and 7, are using threading and fired immediately after each other. Response 11 shows the same request without threading enabled, notice the 5 second delay.

Very cool, clean, and lean solution to the problem.

도움이 되었습니까?

해결책

You can try execute your "expensive" code in separate thread.

It will be something like this:

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

    return new HttpResponseMessage(HttpStatusCode.OK);

}

다른 팁

I believe @lilo,jacob's answer is not a reliable solution if the background task takes long-time. It may never complete and you lost data. Read this answer please: https://stackoverflow.com/a/25275835/538387

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top