How to prevent simultaneous access in MVC Controller?

I have an MVC controller, accessible at a specific URL, which, when called, starts a series of time-consuming processes (data after processing from db).

I need to make sure that when the method is called by the user, the process starts once. If any other users gain access to the specified URL during post-processing, then subsequent post-processing does not occur.

My questions:

  • Should I use locks in C #?
  • Should I use some inProgress flag in the database, so that I can mark when the beginning and end of processing?
  • Any other solutions?
+7
c # asp.net-mvc asp.net-mvc-4
source share
3 answers

If you want to scale to multiple computers, locking the memory is not an option, but locking in the database is probably the easiest.

For example, you can create a lock table with a unique identifier field. When you receive the request, try inserting the line with the identifier 1. If you succeed, do the post process and delete the key.

Any other request that tries to insert a key during its creation during another launch cannot insert and fail to complete the task.

+5
source share

Each concurrent request will have its own thread.

This is a set of unfinished tasks necessary to ensure thread safety. This resource will be shared, so multiple web requests will try to access at the same time.

.NET 4.0 has parallel collections that make your life easier. You need parallel dialing, however such a class does not exist. Instead, you can use ConcurrentDictionary using only the keys for your request identifiers.

It is assumed that you have only one web server, otherwise you will need a database or a solution for shared services.

+3
source share

More precisely: they are thread safe because the controller created NEW for each request. 2 requests do not use one controller.

+2
source share

All Articles