title: using constrained execute regions
body: <p>I have a Visual Studio 2008 C# .NET 3.5 application that P/Invokes a native method that accepts a file handle as a parameter. Originally, I was just using FileStream.SafeFileHandle.DangerousGetHandle() to get the file handle. But, after turning on FX COP, I got a <a href="http://msdn.microsoft.com/en-us/library/bb385973.aspx" rel="nofollow">CA2001</a> warning about that. So, after a little research I discovered "Constrained execute regions". This is new to me and I haven't seen a whole lot of information about it. I was hoping somebody more experienced could take a look and verify that I've done this correctly. </p>
  
  <pre><code>class MyClass
  {
      public static bool Write(string filename)
      {
          using (var fs = new System.IO.FileStream(filename, 
              System.IO.FileMode.Create, 
              System.IO.FileAccess.Write, 
              System.IO.FileShare.None))
          {
              bool got_handle;
              bool result;
  
              System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
              try { }
              finally
              {
                  fs.SafeFileHandle.DangerousAddRef(ref got_handle);
                  result = NativeMethods.Foo(fs.SafeFileHandle.DangerousGetHandle());
                  if (got_handle)
                      fs.SafeFileHandle.DangerousRelease();   
              }
  
              return result;
          }
      }
  }
  
  internal sealed class NativeMethods
  {
      [DllImport("mylib.dll",
          EntryPoint = "Foo",
          CallingConvention = CallingConvention.StdCall,
          CharSet = CharSet.Unicode,
          ExactSpelling = true, 
          SetLastError = true)]
      public static extern bool Foo(IntPtr hFile);
  }
  </code></pre>
  
  <p>Thanks,
  PaulH</p>