title: In C++/CLI how do you define thread-safe event accessors?
body: <p>The code sample "How to: Define Event Accessor Methods" at</p>
  
  <p><a href="http://msdn.microsoft.com/en-us/library/dw1dtw0d.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/dw1dtw0d.aspx</a></p>
  
  <p>appears to mutate the internal <code>pE</code> without taking locks.  (It doesn't look like <code>Delegate::Combine</code> does anything magical that would prevent issues.)  It also does</p>
  
  <pre><code>void raise() {
     if (pE != nullptr)
        pE-&gt;Invoke();
  }
  </code></pre>
  
  <p>which can be problematic if <code>pE</code> changes to <code>null</code> between the check and the <code>Invoke()</code>.  I have two questions:</p>
  
  <ol>
  <li><p>Am I right in that the existing code is not thread-safe?</p></li>
  <li><p>Since I want a thread-safe version of the code, I was thinking of locking the <code>add</code> and <code>remove</code> functions.  Is it premature optimization to use</p>
  
  <pre><code>void raise() {
      MyDel^ handler = pE;
      if (handler != nullptr)
         handler-&gt;Invoke();
  }
  </code></pre>
  
  <p>or should I just lock that function too?</p></li>
  </ol>