Tag Archives: lock

what is lock?

lock marks a statement block as critical section and ensures one thread doesn’t enter critical section with another thread.
lock can be applied on an object. Avoid lock on public type. Below lock should be avoided:

  • lock (this) is a problem if the instance can be accessed publicly.
  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.
  • lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define private object or private static object variable to protect data common to all instance.

class Account
    {
        decimal balance;
        private Object thisLock = new Object();

        public void Withdraw(decimal amount)
        {
            lock (thisLock)
            {
                if (amount > balance)
                {
                    throw new Exception("Insufficient funds");
                }
                balance -= amount;
            }
        }
    }

for more explanation refer:
http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

Advertisements

Leave a comment

Filed under C#

What makes thread-safe?

  • struct & immutable are thread safe. so string is also thread safe as all you can do is read them.
  • Reading is safe, if all the threads are reading.
  • If a method only access variable scoped within the method then it is thread safe beacuse each thread has it’s own stack.
  • Also if method calls other method which only use local scoped variables.
public class Thing
{
    public int ThreadSafeMethod(string parameter1)
    {
        int number; // each thread will have its own variable for number.
        number = this.GetLength(parameter1);
        return number;
    }

    private int GetLength(string value)
    {
        int length = value.Length;
        return length;
    }
}

 

  • but if a method use any properties or fields then you need to use lock to ensure the values are not modified by a different thread.
public class Thing
{
    private string someValue; // all threads will read and write to this same field value

    public int NonThreadSafeMethod(string parameter1)
    {
        this.someValue = parameter1;

        int number;

        // Since access to someValue is not synchronised by the class,
        // a separate thread could have changed its value.
        number = this.someValue.Length;
        return number;
    }
}

To ensure proper concurrency you need to use lock.

Leave a comment

Filed under C#