Posts tagged ‘Lock’

Smart Resource Locking in C# .Net for Thread Safe Code

Updated 1/8/2012: Removed code formatting to use SyntaxHighlighter and fixed off colors on titles.

So you are into thread safe code and you have begun to lock resources. But the trap that all new programmers sometimes do is to lock the whole class as shown below:

public void DeadlockWaitingToHappen1(string change) 
{     
   lock (this)     
   {         
      _Resource1 = change;     
   } 
} 

public void DeadlockWaitingToHappen2(string change2) 
{     
   lock (this)     
   {         
      _Resource2 = change2;     
   } 
}

The problem with the above code, albeit trite due to the example, is that when a thread 1 calls the first method to change resource1, it will effectively block any other thread calling the opposite method to change _resource2.

Because we know that these resources are independent, such locking in the above case is a nuance, in a more advanced state, causes undo wait times for resources, but in a worse case scenario could cause deadlocks in code!

Solution

To get around that what we will do is to lock separate objects. The below code will create mirror object locks and use those to properly lock our different distinct resources.

// This class simulates the use of two different 
// thread safe resources and how to lock them 
// for thread safety but not block other 
// threads getting different resources. 
public class SmartLocking
{
    private string StrResource1 { get; set; }
    private string StrResource2 { get; set; }

    private object _Lock1 = new object();
    private object _Lock2 = new object();

    public void DoWorkOn1( string change )
    {
        lock (_Lock1)
        {
            _Resource1 = change;
        }
    }

    public void DoWorkOn2( string change2 )
    {
        lock (_Lock2)
        {
            _Resource2 = change2;
        }
    }
}

Summary

As you can see we have separate locks, so now thread 1 accessing resource 1 won’t block thread 2 accessing resource 2.  Note if the object you are working contains the interface to allow locking and it makes sense to use that resource, then lock it instead of a separate object.

Share