/// <summary> /// To be connected to SimulationFinished-Event. Extracts data and logs it in the database /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnSimulationFinished(object sender, SimulationFinishedEventArgs args) { SimulationData simulationData = new SimulationData(); simulationData.ExecutionTime = args.ExecutionTime; using (var hospitalContext = new HospitalContext()) { var deadPatients = (from patient in hospitalContext.Patients where patient.Status == PatientStatus.Afterlife select patient).Count(); var recoveredPatients = (from patient in hospitalContext.Patients where patient.Status == PatientStatus.Recovered select patient).Count(); var timeSpentInQueue = (from patient in hospitalContext.Patients select patient.TimeSpentInQueue).ToList(); simulationData.AmountOfDeadPatients = deadPatients; simulationData.AmountOfRecoveredPatients = recoveredPatients; simulationData.AverageTimeSpentInQueue = CalculateAverageTimeSpan(timeSpentInQueue); hospitalContext.SimulationData.Add(simulationData); hospitalContext.SaveChanges(); //Empties out the patients and doctors-tables after finished simulation hospitalContext.Database.ExecuteSqlCommand("TRUNCATE TABLE Patients"); hospitalContext.Database.ExecuteSqlCommand("TRUNCATE TABLE Doctors"); hospitalContext.SaveChanges(); } string toWrite = $"All patients has left the hospital. This simulation took {args.ExecutionTime.TotalSeconds:0} seconds.\n" + "---------------------------------------------\n\n"; File.AppendAllText(fileName, toWrite); Console.Write(toWrite); }
/// <summary> /// Starts one run of Simulation. Throws SimulationFinished-event when finished /// </summary> public void Start() { SimulationFinishedEventArgs args = new SimulationFinishedEventArgs(); Generator generator = new Generator(); Thread thread1 = new Thread(generator.AddNewPatientsToDatabase); Thread thread2 = new Thread(SimulatePatientSorting); Thread thread3 = new Thread(SimulateSymptomsChanging); Thread thread4 = new Thread(SimulatePatientRecoveringOrDying); Thread thread5 = new Thread(generator.AddNewDoctorsToDatabase); Thread thread6 = new Thread(SimulateDoctorMovement); //Thread-prio for the threads creating patient and doctor-data thread1.Priority = ThreadPriority.Highest; thread5.Priority = ThreadPriority.Highest; thread1.Start(); thread5.Start(); thread2.Start(); thread3.Start(); thread4.Start(); thread6.Start(); //First, wait for thread4 to run to end, which will indicate the end thread4.Join(); //Then thread 2 and 3, so that they can print a last time before ending the simulation thread2.Join(); thread3.Join(); //thread 6 needs to end before completed, if there are doctors left without patients if (thread6.IsAlive) { runDoctorMovement = false; thread6.Join(); } args.SetExecutionTime(); //In order for all threads to finish before invoking SimulationFinished Thread.Sleep(3000); SimulationFinished?.Invoke(this, args); }