title: C# code very slow with debugger attached; MemoryMappedFile's fault?
body: <p>I have a client/server app.  The server component runs, uses WCF in a 'remoting' fashion (binary formatter, session objects).</p>
  
  <p>If I start the server component and launch the client, the first task the server does completes in &lt;0.5sec.</p>
  
  <p>If I start the server component with VS debugger attached, and then launch the client, the task takes upwards of 20sec to complete.</p>
  
  <p>There are no code changes - no conditional compilation changes.  The same occurs whether I have the server component compiled and running in 32-bit, 64-bit, with the VS hosting process, without the VS hosting process, or any combination of those things.</p>
  
  <p><strong>Possibly important</strong>: If I use the VS.NET <em>profiler</em> (sampling mode), then the app runs as quick as if there were no debugger attached.  So I can't diagnose it that way.  Just checked, instrumentation mode also runs quickly.  Same for the concurrency profiling mode, works quickly.</p>
  
  <p>Key data:</p>
  
  <ul>
  <li>The app uses fairly heavy multithreading (40 threads in the standard thread pool).  Creating the threads happens quickly regardless and is not a slow point.  There are many locks, <code>WaitHandle</code>s and <code>Monitor</code> patterns</li>
  <li>The app raises no exceptions at all.</li>
  <li>The app creates no console output.</li>
  <li>The app is entirely managed code.</li>
  <li>The app does map a few files on disk to a MemoryMappedFile: 1x750MB and 12x8MB and a few smaller ones</li>
  </ul>
  
  <p>Measured performance:</p>
  
  <ul>
  <li>CPU use is minimal in both cases; when debugger is attached, CPU sits at &lt;1%</li>
  <li>Memory use is minimal in both cases; maybe 50 or 60MB in both cases</li>
  <li>There are plenty of page faults happening (ref MMF), however they happen more slowly when the debugger is attached</li>
  <li>If the VS hosting process is not used, or basically the 'remote debugging monitor' comes into play, then <em>that</em> uses a decent amount CPU and creates a good number of page faults.  But that's not the only time the problem is occurring</li>
  <li>The performance difference is seen regardless of how the client is run.  The only variable being changed is the server component being run via 'Start with debugging' vs launched from Explorer.</li>
  </ul>
  
  <p>My ideas:</p>
  
  <ul>
  <li>WCF slow when debugged?</li>
  <li>MemoryMappedFiles slow when debugged?</li>
  <li>40 threads used - slow to debug?  Perhaps Monitors/locks notify debugger?  Thread scheduling becomes strange/context switches very infrequent?</li>
  <li>Cosmic background radiation granting intelligence and cruel sense of humour to VS</li>
  </ul>
  
  <p>All seem stupidly unlikely.</p>
  
  <p>So, my questions:</p>
  
  <ol>
  <li>Why is this happening?</li>
  <li>If #1 unknown, how can I diagnose / find out?</li>
  </ol>