Skip to content

Thread safe in Dispose method

George George

Asked May 14, 2008, 4:58 AM EDT2 answers
Share
LinkedInX

Hello everyone,


Here is my code for Dispose method. Currently, I am thinking whether it is necessary to make it thread safe by adding a lock to prevent two threads to execute Dispose methods at the same time?

Notes:

1. disposing is used to indicate explicit call to Dispose or implicit call from Finalizer;

2. disposed is used to indicate whether current instance is Disposed or not, to prevent from disposing again. The thread safety consideration is used to protect this variable.

[Code]
        protected virtual void Dispose(bool disposing)
        {
            lock (DisposeLock)
            {
                if ((false == disposed) && (true == disposing))
                {
   // some operations here
                    disposed = true;
                }
            }
        }
[/Code]


thanks in advance,
George

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    The Dispose Pattern of the CLR does not require thread synchronization as the Finalize routine is not invoked when the object (to be disposed) is in use.
    See Ch.20 in Richter's 'CLR via C#' book.

    SBC
    0
  • 0

    Thanks SB Chatterjee,

     

    I agree if Dispose is invoked through Finalizer, it is thread safe, but what if two threads call Dispose explicitly at the same time?

     

    regards,

    George

    0