我有一个非常简单的代码,有一个明确的任务 - 让10辆赛车异步竞赛。
这是代码:
class Program
{
static void Main(string[] args)
{
int numOfCars = 0;
const int destKm = 1000;
Random rng = new Random();
Console.WriteLine("Write the number of cars in the race");
while (!(int.TryParse(Console.ReadLine(), out numOfCars)))
{
Console.WriteLine("You must enter a valid int. Please try again");
}
Car[] cars = new Car[numOfCars];
int randomNumber;
for (int i = 0; i < numOfCars; i++)
{
randomNumber = rng.Next();
cars[i] = new Car(i, new SynchronizedRandomGenerator(0, 100), destKm);
}
Thread[] raceThread = new Thread[numOfCars];
for (int i = 0; i < numOfCars; i++)
{
raceThread[i] = new Thread(() => cars[i].Race());
raceThread[i].Start();
}
Console.ReadLine();
}
}
public sealed class Car
{
public SynchronizedRandomGenerator RandomGenerator { get; private set; }
public int CarId { get; private set; }
public int DestKm { get; set; }
public Car(int carId, SynchronizedRandomGenerator randomGenerator, int destKm)
{
DestKm = destKm;
CarId = carId;
RandomGenerator = randomGenerator;
}
public void Race()
{
int kmSoFar = 0;
while (kmSoFar < DestKm)
{
kmSoFar += RandomGenerator.Next();
Thread.Sleep(10);
}
Console.WriteLine($"Car {CarId} Has Finished The Race");
}
}
public sealed class SynchronizedRandomGenerator
{
public int MinValue { get; private set; }
public int MaxValue { get; private set; }
Random rng = new Random();
public SynchronizedRandomGenerator(int minValue, int maxValue)
{
rng = new Random();
MinValue = minValue;
MaxValue = maxValue;
}
public int Next()
{
return rng.Next(MinValue, MaxValue);
}
}
我在第raceThread[i] = new Thread(() => cars[i].Race());
行
由于某种原因,它提高了&#34; i&#34;在它进入循环并导致异常之后。但是,当我逐行调试并运行它时,似乎可行。