title: GUI Invoke with EventHandlers
body: <p>I have a class like that "ClientSocket.cs"</p>
  
  <pre><code>  class ClientSocket {
       public delegate void ConnectHandler(object sender, EventArgs e);
       public event ConnectHandler ConnectEvent = delegate { };
  
       protected void OnConnectEvent(EventArgs e) {
          ConnectHandler ev = ConnectEvent;
          ev(this, e);
      }
  
    }
  </code></pre>
  
  <p>And another class "myForm.cs"</p>
  
  <pre><code>public partial class myForm : Form {
      private ClientSocket client;
  
      private void button1_Click(object sender, EventArgs e) {
          client = new ClientSocket();
          client.ConnectEvent += myForm_OnConnectEvent;
  
          client.connect();
      }
  
  
      // Handler for ConnectEvent
      private void myForm_OnConnectEvent(object sender, EventArgs e) {
          //this.BeginInvoke((MethodInvoker)delegate { writeLog("Connected"); }); 
  
          writeLog("Connected");
      }
  
      // Function that write a log string to a TextBox
      public writeLog(string log) {
          guiTextBox.AppendText(log);
      }
    }
  </code></pre>
  
  <p>Here the question.
  I try to call writeLog with BeginInvoke or calling it directly. Sometimes I get an InvalidOperationException when writing to guiTextBox.
  I don't understand why I receive that message. The event is fired by ClientSocket object, but the event handler is relative to the main UI-thread (myForm).</p>
  
  <p>Can I avoid to use BeginInvoke/Invoke for each EventHandler of my class?</p>
  
  <hr>
  
  <p>EDIT: I understand what's the difference, now I'm try to understand the best practice for calling the event.</p>
  
  <p>Should I put the BeginInvoke/Invoke method when <strong>RAISING the event in the BASE class</strong> (ClientSocket in that case)</p>
  
  <pre><code>    protected void OnConnectEvent(EventArgs e) {
          ConnectHandler ev = ConnectEvent;
  
          this.BeginInvoke((MethodInvoker)delegate { ev(this, e);});
      }
  </code></pre>
  
  <p>or should I put that <strong>WHEN I'm using that object and add a listeners to that handler</strong></p>
  
  <pre><code>    // Handler for ConnectEvent used in GUI (myForm)
      private void myForm_OnConnectEvent(object sender, EventArgs e) {
          this.BeginInvoke((MethodInvoker)delegate { writeLog("Connected"); }); 
      }
  </code></pre>
  
  <p>Cheers</p>