Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Data;
- using System.IO;
- namespace ResRegV1cons
- {
- class ResAreBusy : Exception { }
- class ResIdInvalid : Exception { }
- class UnRecommended : Exception { }
- class ResIsBusy : Exception { }
- class ResWasFree : Exception { }
- static class SetUp
- {
- public static string Path; //путь к файлу, сохраняющему модель
- private static void ClearModel()
- {
- Console.WriteLine("Укажите количество ресурсов:");
- try
- {
- Model.vRes_s = new string[Convert.ToInt32(Console.ReadLine())];
- for (int i = 0; i < Model.vRes_s.Length; i++) Model.vRes_s[i] = "F";
- Model.ResList = new List<Tuple<int, int>>();
- }
- catch
- {
- Console.WriteLine("Введено некорректное число!");
- ClearModel();
- }
- }
- private static void GetModel()
- {
- Console.WriteLine("Обновить файл?");
- if (Console.ReadLine().ToUpper() == "Y") ClearModel();
- else
- {
- Model.vRes_s = File.ReadAllLines(Path);
- }
- }
- public static bool On()
- {
- try
- {
- if (File.Exists(Directory.GetCurrentDirectory() + @"\Resmod00"))
- {
- Console.WriteLine("Использовать существующий стандартный файл Resmod00?");
- if (Console.ReadLine().ToUpper() == "Y")
- {
- Path = Directory.GetCurrentDirectory() + @"\Resmod00";
- GetModel();
- return true;
- }
- }
- else
- {
- Console.WriteLine("Создать стандартный файл?");
- if (Console.ReadLine().ToUpper() == "Y")
- {
- Path = Directory.GetCurrentDirectory() + @"\Resmod00";
- ClearModel();
- return true;
- }
- };
- Console.WriteLine("Введите полный адрес нестандартного файла:");
- Path = Console.ReadLine();
- if (File.Exists(Path))
- {
- GetModel();
- return true;
- }
- else
- {
- ClearModel();
- return true;
- }
- }
- catch (IOException) { Console.WriteLine("Файл не открылся."); return false; }
- catch (Exception) { Console.WriteLine("Ошибка ввода-вывода."); return false; }
- }
- }
- static class Model
- {
- public static List<Tuple<int, int>> ResList;
- public static string[] vRes_s;//Модель набора ресурсов
- public static void Occupy(string cn)
- {
- if ((Convert.ToInt16(cn) > vRes_s.Length) | (Convert.ToInt16(cn) < 0)) throw new ResIdInvalid();
- if (vRes_s[Convert.ToInt16(cn) - 1] == "B")
- {
- ResIsBusy e = new ResIsBusy();
- e.Data.Add("resID", Convert.ToInt16(cn));
- throw e;
- }
- vRes_s[Convert.ToInt16(cn) - 1] = "B";
- }
- public static void Free(string cn)
- {
- if ((Convert.ToInt16(cn) > vRes_s.Length) | (Convert.ToInt16(cn) < 0)) throw new ResIdInvalid();
- if (vRes_s[Convert.ToInt16(cn) - 1] == "F") throw new ResWasFree();
- vRes_s[Convert.ToInt16(cn) - 1] = "F";
- }
- public static string Request()
- {
- for (int i = 0; i < vRes_s.Length; i++)
- {
- if (vRes_s[i] == "F") return Convert.ToString(i + 1);
- }
- throw new ResAreBusy(); ;
- }
- }
- class Program
- {
- static TimerCallback tm = new TimerCallback(TimeFreeRes);//Таймер для обработки заявок на ресурсе
- static Timer timer = new Timer(tm, null, Timeout.Infinite, Timeout.Infinite);//Вызов таймера для обработки заявок на ресурсе
- static bool timerFlag = false;
- static void Main(string[] args)
- {
- string Command;
- while (!SetUp.On()) ;
- DateTime StartTime = DateTime.Now;
- do
- { if (timerFlag)
- {
- Command = "Continue";
- continue;
- }
- File.WriteAllLines(SetUp.Path, Model.vRes_s);//сохранение модели
- Console.WriteLine("Введите команду:");
- Command = Console.ReadLine();
- DateTime StopTime = DateTime.Now;
- timer.Change(Timeout.Infinite, Timeout.Infinite);
- Command = Command.ToUpper();
- try
- {
- if (Command == "REQUEST") Console.WriteLine(Model.Request());
- if (Command == "OCCUPY")
- {
- Console.WriteLine("Введите номер ресурса:");
- Model.Occupy(Console.ReadLine());
- Console.WriteLine("Ресурс стал занятым.");
- };
- if (Command == "FREE")
- {
- Console.WriteLine("Введите номер ресурса:");
- Model.Free(Console.ReadLine());
- Console.WriteLine("Ресурс освобождён.");
- };
- }
- catch (OverflowException) { Console.WriteLine("Такого ресурса нет."); }
- catch (FormatException) { Console.WriteLine("Такого ресурса нет."); }
- catch (ResIdInvalid) { Console.WriteLine("Такого ресурса нет."); }
- catch (ResWasFree) { Console.WriteLine("Ресурс был свободен."); }
- catch (ResAreBusy) { Console.WriteLine("Все ресурсы заняты."); }
- catch (ResIsBusy e)
- {
- while (true)
- {
- Console.WriteLine("Ресурс уже занят. Ожидать его освобождения? Y/N?");
- string answer = Console.ReadLine();
- if (answer.ToUpper() == "Y")
- {
- int waitTime;
- while (true)
- {
- Console.WriteLine("Введите время ожидания.");
- try
- {
- waitTime = Convert.ToInt16(Console.ReadLine());
- break;
- }
- catch
- {
- Console.WriteLine("Неверный ввод, попробуйте снова.");
- }
- }
- TimeSpan elapsedTime = StopTime.Subtract(StartTime);
- for (int i = 0; i < Model.ResList.Count; i++)
- {
- Model.ResList[i] = new Tuple<int, int>(Model.ResList[i].Item1, Model.ResList[i].Item2 - (elapsedTime.Seconds));
- }
- Model.ResList.Add(new Tuple<int, int>(Convert.ToInt16(e.Data["resID"]), waitTime));
- Console.WriteLine("Запрос на ресурс {0} успешно добавлен в очередь.", Convert.ToInt16(e.Data["resID"]));
- Model.ResList.Sort(
- (t1, t2) =>
- {
- return t1.Item2.CompareTo(t2.Item2);
- });
- break;
- }
- else if (answer.ToUpper() == "N")
- break;
- else
- Console.WriteLine("Введите ответ снова.");
- }
- }
- if (Model.ResList.Count() == 0)
- timer.Change(Timeout.Infinite, Timeout.Infinite);
- else if (Model.ResList.Count() == 1)
- {
- timer.Change(Model.ResList[0].Item2 * 1000, Model.ResList[0].Item2 * 1000);
- StartTime = DateTime.Now;
- }
- else
- {
- for (int i = 0; i < Model.ResList.Count; i++)
- {
- Console.WriteLine("{0}",Model.ResList[i]);
- }
- timer.Change(Model.ResList[0].Item2 * 1000, Model.ResList[0].Item2 * 1000);
- StartTime = DateTime.Now;
- }
- }
- while (Command != "");
- }
- static void TimeFreeRes(object obj)
- {
- timerFlag = true;
- timer.Change(Timeout.Infinite, Timeout.Infinite);
- if (Model.vRes_s[Model.ResList[0].Item1 - 1] == "B") //((Model.ResList.Count() >= 1) && (Model.vRes_s[Model.ResList[0].Item1-1] == "B"))
- {
- while (true)
- {
- Console.WriteLine("Ресурс {0} все еще занят. Ожидать его освобождения далее? Y/N?", Model.ResList[0].Item1);
- string answer = Console.ReadLine();
- if (answer.ToUpper() == "Y")
- {
- int waitTime;
- while (true)
- {
- Console.WriteLine("Введите время ожидания.");
- try
- {
- waitTime = Convert.ToInt16(Console.ReadLine());
- break;
- }
- catch
- {
- Console.WriteLine("Неверный ввод, попробуйте снова.");
- }
- }
- Model.ResList.Add(new Tuple<int, int>(Model.ResList[0].Item1, waitTime));
- Console.WriteLine("Запрос на ресурс {0} успешно продлен.", (Model.ResList[0].Item1));
- Model.ResList.RemoveAt(0);
- Model.ResList.Sort(
- (t1, t2) =>
- {
- return t1.Item2.CompareTo(t2.Item2);
- });
- break;
- }
- else if (answer.ToUpper() == "N")
- {
- Model.ResList.RemoveAt(0);
- Console.WriteLine("Запрос успешно удален.");
- if (Model.ResList.Count() >= 1)
- timer.Change(0, Model.ResList[0].Item2 * 1000);
- else
- timer.Change(Timeout.Infinite, Timeout.Infinite);
- break;
- }
- else
- Console.WriteLine("Введите ответ снова.");
- }
- }
- else //if (Model.ResList.Count() >= 1)
- {
- Model.vRes_s[Model.ResList[0].Item1-1] = "B";
- Console.WriteLine("Ресурс {0} теперь занят.\nВведите команду:", Model.ResList[0].Item1);
- Model.ResList.RemoveAt(0);
- if (Model.ResList.Count() >= 1)
- timer.Change(0, Model.ResList[0].Item2 * 1000);
- else
- timer.Change(Timeout.Infinite, Timeout.Infinite);
- }
- timerFlag = false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement