1

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];
    }
2
  • Which version of .net you are using? If 4.0 then probably you can reply on TPL rather than trying to manage yours? Commented Jun 25, 2013 at 14:12
  • 4
    On a side note, if you aren't aware of it, you should certainly look into Tasks: msdn.microsoft.com/en-us/library/system.threading.tasks.aspx Commented Jun 25, 2013 at 14:12

1 Answer 1

3

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();
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you the short hand did the job for me! :)
That said, yes, the Task Parallel Library would probably be the way to go for what you are aiming at (as @GeorgeJohnston commented)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.