如何将每个数组元素与函数相关联?

时间:2013-09-07 13:58:40

标签: c# .net arrays delegates

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

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

我有一个方法随机选取一个数字:

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

我将每个令牌与方法相关联:

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

1 个答案:

答案 0 :(得分: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();