void CarsStart() { for (int i = 0; i < countCars; i++) { wakeEvents.Add(new AutoResetEvent(false)); var cateringCar = new CateringCar(i); cateringCar.LocationVertex = transportMotion.GetHomeVertex(); cars.TryAdd(cateringCar.CarId, cateringCar); tokens.TryAdd(cateringCar.CarId, new CancellationTokenSource()); DoCatering(cateringCar, wakeEvents[i]).Start(); } }
Task DoCatering(CateringCar car, AutoResetEvent wakeEvent) //car work { return(new Task(() => { while (true) { //waits for common command if (commands.TryDequeue(out var command)) { Console.WriteLine($"Catering car {car.CarId} is going to airplane {command.PlaneId}"); transportMotion.GoPath(car, command.PlaneLocationVertex); Console.WriteLine($"Catering car {car.CarId} begins catering airplane {command.PlaneId}"); playDelaySource.CreateToken().Sleep(1 * 60 * 1000); //1 min to do catering mqClient.Send <CateringCompletion>(queuesTo[Component.Airplane], new CateringCompletion() { FoodList = command.FoodList, PlaneId = command.PlaneId }); Console.WriteLine($"Catering car {car.CarId} completed catering airplane {command.PlaneId}"); completionEvents[command.PlaneId].Signal(); } if (!IsHome(car.LocationVertex)) //if car is not home go home { Console.WriteLine($"Catering car {car.CarId} is going home"); car.IsGoingHome = true; transportMotion.GoPathFree(car, transportMotion.GetHomeVertex(), tokens[car.CarId].Token); } if (!tokens[car.CarId].IsCancellationRequested) //if going home was not cancelled wait for task { car.IsGoingHome = false; wakeEvent.WaitOne(); } else { Console.WriteLine($"Catering car {car.CarId} going home was cancelled"); tokens[car.CarId] = new CancellationTokenSource(); } } })); }