Poser: What is the lifetime of local instances?


A reader wote me to ask a question about variable lifetimes. Consider the following code:

class Mutex

{

       public Mutex(string name)

       {

             hMutex = Kernel32.CreateMutex(null,false,name);

             Kernel32.WaitForSingleObject(hMutex,0);

       }

       ~Mutex()

       {
             Kernel32.ReleaseMutex(hMutex);

       }

}

class MyClass

{
       void MyFunc()

       {

             Mutex m = new Mutex(“MyGlobalMutex”);

             

             // (some code here which accesses, or calls functions which access, a shared resource…

             // Note: no explicit reference to m, especially no call to destroy or clean up m!)

       }

}


Will the mutex will be held for the duration of method MyFunc()?


Answer to follow in the next post


 

Comments (2)

  1. Besides that this obviously doesn’t work (as you explain in your answer), the mutex class is also broken. In this example, the Mutex finalizer can actually run *before* the call to Kernel32.WaitForSingleObject. You need to use GC.KeepAlive(this) at the end of the constructor.