0

I have an array and numbers stored in it:

int[] numbers = new int[5]  {1, 2, 3, 4, 5 };

I have a method randomly pick up a number:

Random rnd = new Random();
int r = rnd.Next(numbers.Length);
int Token = (numbers[r]);

I have each Token associated with a method:

if (Token == 1) 
{
    ThreadStart Ref1 = new ThreadStart(f.VehicleThread1);
    Thread Th1 = new Thread(Ref1);
    Th1.Start();
}
if (Token == 2)
{
    ThreadStart Ref2 = new ThreadStart(f.VehicleThread2);
    Thread Th2 = new Thread(Ref2);
    Th2.Start();
}
if (Token == 3)
{
    ThreadStart Ref3 = new ThreadStart(f.VehicleThread3);
    Thread Th3 = new Thread(Ref3);
    Th3.Start();
}
if (Token == 4)
{        
    ThreadStart Ref4 = new ThreadStart(f.VehicleThread4);
    Thread Th4 = new Thread(Ref4);
    Th4.Start();
}
if (Token == 5)
{
    ThreadStart Ref5 = new ThreadStart(f.VehicleThread5);                     
    Thread Th5 = new Thread(Ref5);
    Th5.Start();
}

But if I try aborting the thread outside this, it's generating an error message which is obvious.

if (Token == 1)
    list.RemoveAt(0);

numbers = list.ToArray(typeof(int)) as int[]; 
Th1.Abort();   
1
  • 2
    Can't you just create an array of Func or Action in case you don't need the return value? Commented Sep 7, 2013 at 14:00

1 Answer 1

5

You could just create an array of ThreadStart delegates instead:

ThreadStart[] delegates = new ThreadStart[5] 
{
    f.VehicleThread1, 
    f.VehicleThread2, 
    f.VehicleThread3, 
    f.VehicleThread4, 
    f.VehicleThread5 
};

Thread th = new Thread(delegates[Token - 1]); // -1 because array indexes start at 0
th.Start();

Or perhaps a Dictionary<int, ThreadStart>:

Dictionary<int, ThreadStart> delegates = new Dictionary<int, ThreadStart>() 
{
    { 1, f.VehicleThread1 }, 
    { 2, f.VehicleThread2 }, 
    { 3, f.VehicleThread3 }, 
    { 4, f.VehicleThread4 }, 
    { 5, f.VehicleThread5 }
};

Thread th = new Thread(delegates[Token]); // -1 not needed here
th.Start();
Sign up to request clarification or add additional context in comments.

Comments

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.