Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent concurrent access in MVC Controller?

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?
like image 761
GibboK Avatar asked May 30 '14 16:05

GibboK


People also ask

How to handle concurrency in MVC?

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.


2 Answers

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.

like image 139
Joachim Isaksson Avatar answered Oct 18 '22 20:10

Joachim Isaksson


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.

like image 3
James L Avatar answered Oct 18 '22 19:10

James L