title: Forcing single-thread access to a resource
body: <p>Currently I have multiple resources in a project that can only be accessed from a single thread. One example is a ZeroMQ server and another is a Mitsubishi PLC communication module that's not threadsafe.</p>
  
  <p>Right now I create a seperate thread for any resource requiring single-threaded access. I haven't wrapped this in a class or anything, so I have a <code>ThreadStart</code> (void) method and a couple of properties in every class requiring coordinated access to a resource. I then use a dispatcher combined with <code>Invoke</code> / <code>BeginInvoke</code> to force access from the seperate Thread only.</p>
  
  <p><strong>Is there some class already available that can coordinate access to a resource from a single thread?</strong></p>
  
  <p>Here's some sample code that will get me a Dispatcher right now:</p>
  
  <pre><code>object theLock = new object();
  Dispatcher dispatcher = null;
  
  lock (theLock)
  {
      new Thread(new ThreadStart(() =&gt;
      {
          lock (theLock)
          {
              dispatcher = Dispatcher.CurrentDispatcher;
              Monitor.Pulse(theLock);
          }
          Dispatcher.Run();
      })).Start();
  
      Monitor.Wait(theLock);
  }
  
  dispatcher.Invoke(...);
  </code></pre>
  
  <p>I can wrap this code in a class just to create a thread and dispatcher whenever I need one, but I can't imagine this being the best solution to coordinate access to a thread-unsafe resource.</p>