Question

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?

Was it helpful?

Solution

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;
        }
    }
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top