Reputation: 683
I have an application runs ASP.NET Web API on the backend. There's a specific controller that looks something like
public class MyController : ApiController
{
dynamic Post(dynamic postParams)
{
var data = retrieveData(postParams.foo, postParams.bar);
writeDataToDb(data);
return data;
}
}
So there are three operations, the retrieval of data based on the post parameters, writing the retrieved data to a DB, and returning the retrieved data as JSON to the client.
This could be greatly sped up if the DB write step was not blocking returning the JSON to the client, as they are not dependent on one another.
My concern is that if I spin off the DB write off in another thread that the Post method returning will cause the process to tear-down and could potentially kill the DB write. What's the correct way to handle this scenario?
Should I have a separate handler that I shoot an async web request to so that the DB write will occur in its own process?
Upvotes: 2
Views: 146
Reputation: 149538
I would generate a seperation of concerns. Let one method query the data from the DB (suitable for a GET method), and another for updating the data in your DB (suitable for a POST or UPDATE method). That way, retrieving your data would be a lighter operation and less time conuming.
As a side note, spinning of new threads without registering them with the ASP.NET ThreadPool is dangerous, as IIS may decide to recycle your app at certain times. Therefore, if you're on .NET 4.5.2, make sure to use HostingEnvironment.QueueBackgroundWorkItem
to queue work on the ThreadPool. If not, you can use stephan clearys BackgroundTaskManager
. Also, i suggest reading more in stephans article Fire and Forget on ASP.NET
Upvotes: 1