4

For locking I am using a single static object which is global to my application:

public class MvcApplication : System.Web.HttpApplication
{        
    public static readonly object AppLock = new object();
    ...
}

Using it for locking in code:

lock(MvcApplication.AppLock)
{
    ...
}

Let us not consider performance impact for a moment. Can I be 100% sure that I will avoid deadlock in this case?

Evgenii
  • 36,389
  • 27
  • 134
  • 170
  • 1
    The definition of a deadlock is as L.B posted below. Are you sure that's what you are safeguarding against? If not, what situation do you need to avoid? – Kieren Johnstone Nov 09 '11 at 11:38
  • I want to use this technique to avoid any kind of deadlocks in my application. – Evgenii Nov 09 '11 at 14:12
  • Of course, given that all locks in my app use MvcApplication.AppLock object only. – Evgenii Nov 09 '11 at 14:18
  • I don't think you understand a deadlock then. If you're adding a `lock` to remove deadlocks, then you don't understand that for a deadlock you need to have two `lock`s to begin with. Or are you talking about SQL Server deadlocks, something very different? – Kieren Johnstone Nov 09 '11 at 15:41
  • Oh, sorry for confusion. I meant that I have more than one lock block in my web application, a lot of them, actually. I just wanted to make sure that it would not deadlock in any condition. And yes, I meant only my C# code in asp.net mvc project, not the sql deadlock. – Evgenii Nov 10 '11 at 11:36

2 Answers2

12

You can not create a deadlock conditon just with one lock-object(AppLock) See http://en.wikipedia.org/wiki/Deadlock . But it is possible with this kind of codes in threads

lock(A)
   lock(B)
       DoSomething();


lock(B)
   lock(A)
       DoSomething();
L.B
  • 114,136
  • 19
  • 178
  • 224
0

Don't know if it's possible in ASP.NET but in winforms/wpf you can do it.

'Deadlock' with only one locked object?

Another deadlocking scenario arises when calling Dispatcher.Invoke (in a WPF application) or Control.Invoke (in a Windows Forms application) while in possession of a lock. If the UI happens to be running another method that’s waiting on the same lock, a deadlock will happen right there. This can often be fixed simply by calling BeginInvoke instead of Invoke. Alternatively, you can release your lock before calling Invoke, although this won't work if your caller took out the lock. We explain Invoke and BeginInvoke in Rich Client Applications and Thread Affinity.

source: http://www.albahari.com/threading/part2.aspx

WhileTrueSleep
  • 1,524
  • 1
  • 19
  • 32