0

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.

C sharper
  • 104
  • 1
  • 2
  • 9
  • Do you mind sharing the exception you are getting? – Michael Aug 24 '15 at 13:26
  • No problem - say I wrote in console that I have 10 cars. The code was falling at the line "new Thread(() => cars[i].Race() " because it was try to execute cars[10].Race() so I would recive stack overflow. The solution I've been refered to help me with that by writing int a = i and new Thread(() => cars[a].Race(). But now I'm using even simpler solution: raceThread[i] = new Thread(cars[i].Race); – C sharper Aug 24 '15 at 19:24

0 Answers0