I have a very simple code with a clear task - to make 10 cars race asynchronous.
this is the code:
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);
}
}
I recive exception at the line raceThread[i] = new Thread(() => cars[i].Race());
for some reason, it raise the value of "i" after it entered the loop and causing the exception. However when I'm debug and run it line by line it seems to work.