0

In an application a user can create an order. When the order is created it is on pending for payment status. Since a pending order locks the product, a user can only have one order in pending for payment. This order can either be paid or be cancelled (in a limited time). The method that creates the order checks this in the DB and if there is no other pending order, it creates a bunch of rows and then redirects to payment gateway. This could produce a race condition, so two threads check the DB at the same time and they both create the order. I wanted to know can I decorate my CreateOrder method with the [MethodImplAttribute(MethodImplOptions.Synchronized)] attribute to solve the problem? Is this OK? Are there any issues that I'm not aware of?

There is no code yet, I'm in the design process and I'm evaluating my options. I read this and it is very complex. I also read this which seems very simple. Could you please tell me why the answer is no? I got suspicious that life can't be that easy and there is probably a gotcha somewhere. :D

Mara09
  • 65
  • 6
  • If you want any chance at all of getting a "yes" answer, you're going to have to provide a lot more detail about your specific situation, and that necessarily involves actual code. But in all likelihood, the answer will still be "no". – madreflection Jun 02 '22 at 19:33
  • @madreflection - question updated – Mara09 Jun 02 '22 at 19:53
  • 3
    This attribute mostly exists for backwards compatibility with & easy porting of Java code, where the `synchronized` keyword exists. .NET code has never had a need of this, not even in Framework, as there are accepted "native" patterns like `lock`ing on a private `object` field. Even if it worked, it wouldn't solve your particular problem -- you don't need to synchronize threads in your backend, you need to ensure your DB access is atomic. That means using transactions. – Jeroen Mostert Jun 02 '22 at 19:55
  • 1
    According to the docs, this attribute locks on the `Type` of the containing type for static methods and the instance (`this`) for instance methods. These are both inadvisable because other code paths could lock on them and block your method either inadvertently or maliciously. Use a private lock object instead. But also, like Jeroen Mostert said, the issue is not at the method level, it's at the database level. – madreflection Jun 02 '22 at 19:58

0 Answers0