title: Why did entering a lock on a UI thread trigger an OnPaint event?
body: <p>I came across something I simply don't understand.
  In my application I have several threads all adding (and removing) items to a shared collection (using a shared lock).
  The UI thread uses a timer, and on every tick it uses the collection to update its UI.</p>
  
  <p>Since we don't want the UI thread to hold on to the lock for a long time and block the other threads, the way we do it, is that first we acquire the lock, we copy the collection, we release the lock and then work on our copy.
  The code looks like this:</p>
  
  <pre><code>public void GUIRefresh()
  {
      ///...
      List&lt;Item&gt; tmpList;
      lock (Locker)
      {
           tmpList = SharedList.ToList();
      }
      // Update the datagrid using the tmp list.
  }
  </code></pre>
  
  <p>While it works fine, we noticed that sometimes there are slowdowns in the application, and when we managed to catch a stacktrace, we saw this:</p>
  
  <pre><code>....
  at System.Windows.Forms.DataGrid.OnPaint(PaintEventArgs pe)
  at MyDataGrid.OnPaint(PaintEventArgs pe)
  at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
  at System.Windows.Forms.Control.WmPaint(Message&amp; m)
  at System.Windows.Forms.Control.WndProc(Message&amp; m)
  at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)
  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  at System.Threading.Monitor.Enter(Object obj)
  at MyApplication.GuiRefresh()   
  at System.Windows.Forms.Timer.OnTick(EventArgs e)
  at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message&amp; m)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg)
  at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
  at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
  at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
  at System.Windows.Forms.Application.Run(Form mainForm)
  ....
  </code></pre>
  
  <p>Note that entering the lock (Monitor.Enter) is followed by NativeWindow.Callback which leads to OnPaint.</p>
  
  <ul>
  <li><p>How is that possible? Does the UI thread gets hijacked to check its message pump? Does that make sense? Or is there something else here?</p></li>
  <li><p>Is there a way to avoid it? I don't want the OnPaint to be called from within the lock.</p></li>
  </ul>
  
  <p>Thanks.</p>