0

我有一个数组和数字存储在其中:

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

我有一个随机取号的方法:

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

我让每个 Token 都与一个方法相关联:

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();
}

但是,如果我尝试在此之外中止线程,它会生成一条明显的错误消息。

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

numbers = list.ToArray(typeof(int)) as int[]; 
Th1.Abort();   
4

1 回答 1

5

ThreadStart您可以只创建一个委托数组:

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();

或者也许是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();
于 2013-09-07T14:01:51.933 回答