Listing 4: Inventing lock blocks and synchronizing on them

#using <mscorlib.dll>
using namespace System;
using namespace System::Threading;

__gc class Th04
{
private:
   static Object *fileLock = new Object;

public:
   static void M1()
   {
      // ...
      Monitor::Enter(fileLock);
      try
      {
         // read from a file
      }
      __finally
      {
         Monitor::Exit(fileLock);
      }
      // ...
   }

   static void M2()
   {
      // ...
      Monitor::Enter(fileLock);
      try
      {
         // update a display
      }
      __finally
      {
         Monitor::Exit(fileLock);
      }
      // ...
   }
};
— End of Listing —