title: C# - Events and delegates when receiving data
body: <p>I want to display a string when I receive data from a server. For that I was thinking on using delegates and events. I'm new to this topic (Delegates and Events) so I'm have not been able to set this up.
  Here is what I've done:</p>
  
  <pre><code>public delegate void ClientHandleData(byte[] data, int bytesRead);
  public event ClientHandleData OnDataReceived;
  
  public void ConnectToServer(string ipAddress, int port)
  {
      this.port = port;
      tcpClient = new TcpClient(ipAddress, port);
      clientStream = tcpClient.GetStream();
  
      Thread t = new Thread(new ThreadStart(ListenForData));
      started = true;
      t.Start();
  }
  private void ListenForData()
  {
     int bytesRead;
  
     while (started)
     {
        bytesRead = 0;
  
        try
        {
            bytesRead = clientStream.Read(buffer.ReadBuffer, 0, readBufferSize);      
        }
        catch
        {
          //A socket error has occurred
          MessageBox.Show("A socket error has occurred);
          break;
        }
  
        if (OnDataReceived != null)
        {
  
                  // display string to a textbox on the UI
        }
  
      Thread.Sleep(15);
     }
  
     started = false;
  
     Disconnect();
  }
  </code></pre>