0

I have the following action in my Web Api controller:

[HttpPost]
[Route("api/geom")]
public HttpResponseMessage AddRef([FromBody]Peticion empObj)
{
    using (SqlConnection con = new SqlConnection("Server=xx;database=xx;User Id=xx;Password=xx"))
    {
        string query = "UPDATE [dbo].[tmp_parcelas] SET[geom] = geometry::STGeomFromText('" + empObj.geom + "',25830) WHERE[idparcela] = " + empObj.id + ";";
        using (SqlCommand querySaveStaff = new SqlCommand(query))
        {
            querySaveStaff.Connection = con;
            con.Open();
            querySaveStaff.ExecuteNonQuery();
            con.Close();
        }
    }
    return Request.CreateResponse(HttpStatusCode.OK);
}

It receives a lot of requests in a very short period of time (like 60 in 1 second or so), so I guess it is necessary to make the method asynchronous.

How can I make the controller action run asynchronously?

Thanks in advance.

1 Answer 1

3

In order to make it truly asynchronous, you need to do few things:

  1. Change return type of the method to Task<HttpResponseMessage>
  2. Mark it with async keyword so you can asynchronously wait (await) on other tasks inside of it
  3. Use asynchronous version of methods for opening database connection and query execution

So, after refactoring, method should look like this:

[HttpPost]
[Route("api/geom")]
public async Task<HttpResponseMessage> AddRef([FromBody]Peticion empObj)
{
    using (SqlConnection con = new SqlConnection("connection-string"))
    {
        string query = "query";
        using (SqlCommand querySaveStaff = new SqlCommand(query))
        {
            querySaveStaff.Connection = con;
            await con.OpenAsync();
            await querySaveStaff.ExecuteNonQueryAsync();
            con.Close(); // in this case not needed will be closed when disposed
        }
    }
    return Request.CreateResponse(HttpStatusCode.OK);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.