title: Is there a good method in C# for throwing an exception on a given thread
body: <p>The code that I want to write is like this:</p>
  
  <pre><code>void MethodOnThreadA()
  {
      for (;;)
      {
          // Do stuff
          if (ErrorConditionMet)
              ThrowOnThread(threadB, new MyException(...));
      }
  }
  
  void MethodOnThreadB()
  {
      try
      {
          for (;;)
          {
              // Do stuff
          }
      }
      catch (MyException ex)
      {
          // Do the right thing for this exception.
      }
  }
  </code></pre>
  
  <p>I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated.  Is there a better mechanism that I can use?</p>
  
  <p>Here is a more fleshed out example of periodically checking:</p>
  
  <pre><code>Dictionary&lt;Thread, Exception&gt; exceptionDictionary = new Dictionary&lt;Thread, Exception&gt;();
  
  void ThrowOnThread(Thread thread, Exception ex)
  {
      // the exception passed in is going to be handed off to another thread,
      // so it needs to be thread safe.
      lock (exceptionDictionary)
      {
          exceptionDictionary[thread] = ex;
      }
  }
  
  void ExceptionCheck()
  {
      lock (exceptionDictionary)
      {
          Exception ex;
          if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex))
              throw ex;
      }
  }
  
  void MethodOnThreadA()
  {
      for (;;)
      {
          // Do stuff
          if (ErrorConditionMet)
              ThrowOnThread(threadB, new MyException(...));
      }
  }
  
  void MethodOnThreadB()
  {
      try
      {
          for (;;)
          {
              // Do stuff
              ExceptionCheck();
          }
      }
      catch (MyException ex)
      {
          // Do the right thing for this exception.
      }
  }
  </code></pre>