Marc Rasmussen
Marc Rasmussen

Reputation: 20555

C# array of threads

So I am creating a class called Operator this class contains a fixed amount of different threads.

I want a method in my Operator that starts all of my threads by looping through the array.

I am new to C# and cannot seem to make this work, I am originally a java programmer and in java I would have been able to do it like this:

    Private Thread[] threadArray;
    Public someConstructor(){
   Thread t1 = new Thread();
   Thread t2 = new Thread();
this.threadArray = new Thread[t1, t2]


} 
public void runThreads(){

    for (Thread t : threadArray) {
        t.start();
    }
}

However, in C# I am unable to do this here is my code example:

   private Thread tHenvendelser;
    private Thread[] threadArray;
    /// <summary>
    /// Operator constuctor.
    /// </summary>
    /// 
    public Operator() { )
    this.tHenvendelser = new Thread()
    this.threadArray = new Thread[tHenvendelser];
    }

Upvotes: 1

Views: 938

Answers (1)

Jcl
Jcl

Reputation: 28272

Here you are creating an array with "tHenvendelser" number of items.

this.threadArray = new Thread[tHenvendelser];

I suspect (hard to say) you really want:

this.threadArray = new Thread[1];
this.threadArray[0] = tHenvendelser;

Or the shorthand:

this.threadArray = new Thread[] { tHenvendelser };

... while we are at it, the C# syntax for the foreach would be:

public void runThreads()
{
  foreach(Thread t in threadArray) {
    t.start();
  }
}

Upvotes: 3

Related Questions