How to prevent concurrent access in MVC Controller?
.net, asp.net-mvc, asp.net-mvc-4, c#
Solution
If you want to scale to multiple machines, an in memory lock is not an option, but a lock in the database is probably the simplest.
For example, you could create a lock table with a unique id field. When you get a request, try to insert a row with id 1. If you succeed, postprocess and delete the key.
Any other request that tries to insert the key while they key exists during another run will fail the insert and not run the job.
Problem
I have a MVC controller accessible at a specific URL, which when called, runs a series of time consuming process (post-processing data from a db). I need to make sure that when the method is being called by an User, the process start once. If any other Users access that specific URL when the post-processing is running no simultaneously post-processing occurs. My questions: - Should I use locks in C#? - Should I use some like inProgress flag in DB, so I can mark when the processing start and end? - Any other solutions?