문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top