fen1ksss
fen1ksss

Reputation: 1120

Two parameters to a C# thread

I can send one parameter in the thread

class myThread
{
    Thread thread;
    public myThread(string name, int st)
    {
        thread = new Thread(this.Get_IP);
        thread.Name = name;
        thread.Start(st);//передача параметра в поток
        thread.Join();
    }
    void Get_IP(object st)
    {
        for (int ii = 0; ii < (int)st; ii++)
        {
            // smth
        }
    }
}

But i need to send two of them for example

for (int ii = (int)st; ii < (int)fi; ii++)
{
    // smth
}

there is a way to put 2 params all together

void A(int a, int b) { }

and

ThreadStart starter = delegate { A(0, 10); };

But how can i send them to the thread?

Upvotes: 0

Views: 144

Answers (5)

Mitja Bonca
Mitja Bonca

Reputation: 4546

If you need to send 2 parametes, you can send them as any type you like, but in the method that starts new thread, you have to unbox it/them:

    void MyMethod()
    {           
        int a = 1;
        int b = 2;
        int[] data = new[] { a, b };
        Thread t = new Thread(new ParameterizedThreadStart(StartThread));
        t.Start(data);
    }

    private void StartThread(object obj)
    {
        int[] data = obj as int[];
        if (data != null)
        {
            int a = data[0];
            int b = data[1];
        }
    }

NOTE: method that is called by new Thread can only accppt object parameter. What is inside this object is not code`s concern, can be anything, like I boxes 2 integers. Then you simply unbox the object to your original data types.

Upvotes: 1

Guffa
Guffa

Reputation: 700292

Put the two variables as members in the class:

class MyThread {

  private Thread _thread;
  private int _start, _finish;

  public MyThread(string name, int start, int finish) {

    _start = start;
    _finish = finish;

    _thread = new Thread(Get_IP);
    _thread.Name = name;
    _thread.Start();
    _thread.Join();
  }

  void Get_IP() {
    for (int ii = _start; ii < _finish; ii++) {
      // smth
    }
  }

}

Note: Calling Join right after starting the thread makes is pretty pointless to use a thread.

Upvotes: 2

Michal Klouda
Michal Klouda

Reputation: 14521

The Thread.Start method accepts an object as parameter. You can pass an array of your values.

thread.Start(new object[] { a, b });

Upvotes: 2

adashie
adashie

Reputation: 616

You can pass more parameters to thread by using lambda expresion. Like this:

Thread thread = new Thread(()=>A(5,6));

Upvotes: 3

Kevin
Kevin

Reputation: 562

Create a class that hold all of the values you need to pass and pass an instance of that class to your thread.

Upvotes: 1

Related Questions