1

I'm creating an object like this:

       if (_cleaner == null)
        {
            _creation.WaitOne();
            try
            {
                if (_cleaner == null)
                {
                   //create object
                }
            }
            finally
            {
                _creation.ReleaseMutex();
            }
        }

The reason i do the double check is because two threads can come simultaneously to the object creation and then I need obviously only one to create an object. Is there a better way to do it? So i dont have to check object existence twice?

Jaroslav Kubacek
  • 1,387
  • 18
  • 26
NeatNerd
  • 2,305
  • 3
  • 26
  • 49
  • That should be fine. That's optimistic pessimistic approach – 123 456 789 0 Apr 19 '14 at 15:07
  • 1
    why are using Mutex? do you need this for cross-process synchronization? – argaz Apr 19 '14 at 18:27
  • doesnt matter, you can use lock, but the performance is gonna be the same – NeatNerd Apr 19 '14 at 18:34
  • 1
    actually because Mutex handles cross-process synchronization, it will be slightly slower than lock, see http://stackoverflow.com/questions/800383/what-is-the-difference-between-mutex-and-critical-section. Anyway, because you don't really need this you can use Lazy which is cleaner and not error prone like double check locking. – argaz Apr 19 '14 at 19:16
  • can u eleborate on Lazy usage in this context, it might be the right direction – NeatNerd Apr 19 '14 at 20:10
  • added some info as an answer – argaz Apr 20 '14 at 12:22

2 Answers2

3

You may want to use Lazy<T>, it's cleaner syntax and less error-prone than double check locking.

It helps you create an object which is initialized only once when being first accessed (lazy initialization), I think that the syntax is quite self-explanatory, some usage examples are in this MSDN article, I'll cite the example:

class Customer
{
    private Lazy<Orders> _orders;
    public string CustomerID {get; private set;}
    public Customer(string id)
    {
        CustomerID = id;
        _orders = new Lazy<Orders>(() =>
        {
            // You can specify any additonal  
            // initialization steps here. 
            return new Orders(this.CustomerID);
        });
    }

    public Orders MyOrders
    {
        get
        {
            // Orders is created on first access here. 
            return _orders.Value;
        }
    }
}
argaz
  • 1,458
  • 10
  • 15
  • Im not sure if thats thread safe, what ThreadSafetyMode shall I use (http://msdn.microsoft.com/en-us/library/system.threading.lazythreadsafetymode(v=vs.110).aspx) and how the overhead is gonna affect performance? – NeatNerd Apr 21 '14 at 10:15
  • You can go with the default (not passing ThreadSafetyMode to the constructor of Lazy) which is ThreadSafetyMode.ExecutionAndPublication and is thread-safe. http://msdn.microsoft.com/en-us/library/dd642329%28v=vs.110%29.aspx – argaz Apr 21 '14 at 13:33
0

Maybe use a framework(e.g. Unity) that has a lifetime manager to help manage your objects? BTW, Unity does a lot more.

Unity - Lifetime manager

Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
  • Thats more like Singleton pattern, isnt it? – NeatNerd Apr 19 '14 at 15:20
  • Unity lets you resolve objects while putting lifetimemanagers on each object(it also gives you the option for di and other stuff). The resolve function is thread safe, so you can basically define that class A will generate singleton objects and class B will generate HTTPContext objects. You can also build your own custom lifetime manager by just implementing a simple interface. The usage is simple - you resolve you object by types. – Amir Popovich Apr 19 '14 at 15:23