Updating GUI from different Class and Thread in c#
<p>Im new to programming and just wanted to know if a solution for a problem I got is appropriate.</p>

<p>I wanted to write a status (string) into a textbox from a class which is creating a Socket and the class listens for data to receives (in an other thread).</p>

<p><em>This is what i did:</em></p>

<p>Create the Class whithin the Form.cs with a button click:</p>

<pre><code> private void button_Create_Click(object sender, EventArgs e)
    {
        int port;
        Int32.TryParse(textBox_Port.Text, out port);
        ServerSocketClass serverSocket = new ServerSocketClass(port, this);
    }
</code></pre>

<p>The ServerSocketClass looks like:</p>

<pre><code>class ServerSocketClass
{
    Socket ServerSocket;
    Socket Accepted;
    IPEndPoint LocalEndpoint;
    int Port = 1337; // just for fun
    Messenger MainForm;

    public ServerSocketClass(int port, Messenger form)
    {

        MainForm = form;

        if (port != 0)
            Port = port;
        ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        LocalEndpoint = new IPEndPoint(IPAddress.Any, Port);

        MainForm.writeToMessages("Binding Endpoint to Socket...");
        ServerSocket.Bind(LocalEndpoint);

        MainForm.writeToMessages("Starting ServerListener Thread...");
        Thread ServerListenThread = new Thread(startListening);
        ServerListenThread.Name = "ServerListenerThread";
        ServerListenThread.Start();        
    }

    private void startListening()
    {            
        ServerSocket.Listen(5);

        MainForm.writeToMessages("Whaiting for incoming connections...");
        Accepted = ServerSocket.Accept();
        whaitForData();
    }
</code></pre>

<p>and to update the GUI in the forms class i created a delegate and a "update" method with an invoke:</p>

<pre><code>public delegate void writeMessege(string message);    
public writeMessege MessegeDelegate;
public void writeToMesseges(string messege)
    {
        if (InvokeRequired)
        {
            this.Invoke(MessegeDelegate, new object[] { messege });
            return;
        }
        textBox_Messeges.AppendText("SYSTEM: " + messege + "\n");
    }
</code></pre>

<p>It works, but I wanted to know if this is a "valid" way to do it or if I should go to the developer hell ;-)</p>

<p>thanks in advance</p>

<p>Locke</p>