Thursday, January 7, 2010

Double Check

有的时候,你想节省资源开销,对于有的对象希望是“按需创建”,而且你的程序是多线程的,你又希望能够是“线程安全”的,这里有一个方法,就是Double Check

private object m_mutex = new object();

private bool m_initialized = false;

private BigInstance m_instance = null;

public BigInstance Instance

{

    get {

            if (!this.m_initialized)

            {

                lock (this.m_mutex)

                {

                    if (!this.m_initialized)

                    {

                        this.m_instance = new BigInstance();

                        this.m_initialized = true;

                    }

                }

            }

            return this.m_instance;

        }

} 

代码来自老赵的cnblog博客

No comments:

Post a Comment