title: RichTextBox Control in a Multi-Threaded Application
body: <p>I'm using a RichTextBox control in a Windows Service to convert RTF to plain text. This method is actually mentioned by MS here: <a href="http://msdn.microsoft.com/en-us/library/cc488002.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc488002.aspx</a></p>
  
  <p>My Windows Service spawns multiple threads (typically 2 x the number of CPU cores), and each of these threads ends up instantiating a separate instance of the RichTextBox control and using it to convert RTF to plain text.</p>
  
  <p>This seems to work great, except for when the service is run on machines with many cores. (4+). In these scenarios, the service will occasionally just lock up. The CPU spins at roughly 10%, and nothing happens. This will go on forever unless you kill the process. I finally managed to attach a debugger while it was happening, and it turns out it is something the RichTextBox control is doing. Looks like some internal lock that's placed when creating a new window handle.</p>
  
  <p>I'm making sure that I dispose of the RichTextBox after every use. This doesn't seem to happen if I force the service to use fewer threads, but this dramatically reduces the throughput of my service on multi-core machines.</p>
  
  <p>Anybody have any ideas on how to fix this, or any idea on a better way to convert RTF to plain text?</p>
  
  <p>Here is the relevant portion of the stack trace of one of the threads that's stuck:</p>
  
  <pre><code>  [In a sleep, wait, or join] 
  &gt; System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.CreateHandle(System.Windows.Forms.CreateParams cp) Line 702 + 0x24 bytes C#
    System.Windows.Forms.dll!System.Windows.Forms.Control.CreateHandle() Line 5632 C#
    System.Windows.Forms.dll!System.Windows.Forms.TextBoxBase.CreateHandle() Line 1478 C#
    System.Windows.Forms.dll!System.Windows.Forms.RichTextBox.Rtf.set(string value) Line 759 C#
  </code></pre>