0

I need to be able to lock certain set of codes in an MVC action depending on the value of a variable

Below code will lock the entire action

public ProductsController : Controller
{
    private static object Lock = new object();

    public ActionResult MyAction(int id)
    {

      lock (Lock)
      {
        //  do my work
      }    
  }
}

But I want to allow concurrent threads to be run parallel when value of the 'id' changes

For example lets assume above controller receives below four requests at the same time

request A : id=1
request B : id=1
request C : id=2 
request D : id=2

with above code these four requests will be processed one after another

But I want (A,B) and (C,D) to run in parallel like below

request A & B need to wait till one of them finish their work to get processed 
request C & D need to wait till one of them finish their work to get processed 

Is this achievable in an MVC environment?

mini998
  • 511
  • 1
  • 5
  • 11
  • 3
    An MVC controller really isn't the right place for business logic like this. – mason Jan 10 '18 at 14:56
  • The OP hasn't requested to do this in the controller, just in an MVC Environment. This seems a reasonable thing to want to do. – bornfromanegg Jan 10 '18 at 15:17
  • 1
    @bornfromanegg But they *have* specifically requested to do this in the controller. It's in the title, and it's in the code shown. – Servy Jan 10 '18 at 15:31
  • locking has to happen when MVC action gets called, the lock code doesn't need to be inside the action, I wrote it there for simplicity. – mini998 Jan 10 '18 at 15:37
  • Servy 's original answer worked for me , only difference I had to declare by ConcurrentDictionary as static since it's a MVC environment. – mini998 Jan 10 '18 at 16:39

0 Answers0