0
votes

I'm new to multi-threading

I have two functions I want to run on different threads (if you must know, they are two tcp socket connections to different ports, one acts as a server the other acts as a client)

First: how can i access a text box on the main form? it does not allow me to access non static members, and i cant create a thread on a non static function

Second: how can i push data to the function while it's running?

I may be approaching this the wrong way, anyway this is my code structure (few lines deleted to simplify)

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
    Thread lis = new Thread(new ThreadStart(Listen));
    Thread con = new Thread(new ThreadStart(Connect));
    public Form1()
    {
        InitializeComponent();
        lis.IsBackground = true;
        con.IsBackground = true;
    }

    static void Connect()
    {
        //try to connect to 127.0.0.1:10500
            while (true)
            {
                //listen and output to Form1.txtControlMessages
                //input from Form1.txtCommandToSend and write to the stream

            }
    }
    static void Listen()
    {
        try
        {
            //start listen server on port 10502
            while (true)
            {
                //accept client and output to Form1.txtData
            }
        }
        catch (SocketException e)
        {
        }

    }
}
1
I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". - John Saunders
I apologize, I didn't know what to put in the title - workoverflow

1 Answers

2
votes

You can create a thread to execute a non-static function. The problem with your code is that your thread instance which is a class field is being initialized with an instance variable/method (Connect and Listen) before the instance can be created.

To fix that simply define your variables at the class level and then initialize them in your constructor.

Thread lis;
Thread con;

public Form1() {
  InitializeComponent();

  lis = new Thread(Listen);
  con = new Thread(Connect);

  lis.IsBackground = true;
  con.IsBackground = true;
}

Also note that you can't access any controls owned by the UI thread from other threads. You'll have to use Control.BeginInvoke in WinForms apps.

private void Connect() {
  // ....

  txtCommandToSend.BeginInvoke(new Action(() => {
    txtCommandToSend.Text = "your string";
  }));

  // ....
}

For you second question. I am not sure what you mean by pushing data to your function while it's running. Once your thread has started, you can't push any data to the function. However, you can use your instance variables from within functions executing under your other threads. You need to be careful though and should use proper locking on these variables if they are accessed by more than one thread.