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:
Test concurrency handlingChange a field in the first browser tab and click Save. The browser shows the Index page with the changed value. Click Save again. The value you entered in the second browser tab is saved along with the original value of the data you changed in the first browser.
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.
Each concurrent request will have its own thread.
It's the set of in-progress tasks you need to make thread safe. This resource will be a shared, so multiple web requests will try to access at the same time.
There are concurrent collections in .Net 4.0 onwards, which make your life easier. What you need is a concurrent set, however no such class exists. You can use ConcurrentDictionary instead, using just the keys for your request IDs.
This assumes you have only one web server, otherwise you will need a database or shared service solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With