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

メソッドに関連付けられた各トークンがあります。

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 に答える