Advertisement
DarkDevourer

Lab PIAPS

May 10th, 2021
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.62 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using System.Data;
  8. using System.IO;
  9.  
  10. namespace ResRegV1cons
  11. {
  12. class ResAreBusy : Exception { }
  13. class ResIdInvalid : Exception { }
  14. class UnRecommended : Exception { }
  15. class ResIsBusy : Exception { }
  16. class ResWasFree : Exception { }
  17. static class SetUp
  18. {
  19. public static string Path; //путь к файлу, сохраняющему модель
  20. private static void ClearModel()
  21. {
  22. Console.WriteLine("Укажите количество ресурсов:");
  23. try
  24. {
  25. Model.vRes_s = new string[Convert.ToInt32(Console.ReadLine())];
  26. for (int i = 0; i < Model.vRes_s.Length; i++) Model.vRes_s[i] = "F";
  27. Model.ResList = new List<Tuple<int, int>>();
  28. }
  29. catch
  30. {
  31. Console.WriteLine("Введено некорректное число!");
  32. ClearModel();
  33. }
  34. }
  35. private static void GetModel()
  36. {
  37. Console.WriteLine("Обновить файл?");
  38. if (Console.ReadLine().ToUpper() == "Y") ClearModel();
  39. else
  40. {
  41. Model.vRes_s = File.ReadAllLines(Path);
  42. }
  43. }
  44. public static bool On()
  45. {
  46. try
  47. {
  48. if (File.Exists(Directory.GetCurrentDirectory() + @"\Resmod00"))
  49. {
  50. Console.WriteLine("Использовать существующий стандартный файл Resmod00?");
  51. if (Console.ReadLine().ToUpper() == "Y")
  52. {
  53. Path = Directory.GetCurrentDirectory() + @"\Resmod00";
  54. GetModel();
  55. return true;
  56. }
  57. }
  58. else
  59. {
  60. Console.WriteLine("Создать стандартный файл?");
  61. if (Console.ReadLine().ToUpper() == "Y")
  62. {
  63. Path = Directory.GetCurrentDirectory() + @"\Resmod00";
  64. ClearModel();
  65. return true;
  66. }
  67. };
  68. Console.WriteLine("Введите полный адрес нестандартного файла:");
  69. Path = Console.ReadLine();
  70. if (File.Exists(Path))
  71. {
  72. GetModel();
  73. return true;
  74. }
  75. else
  76. {
  77. ClearModel();
  78. return true;
  79. }
  80. }
  81. catch (IOException) { Console.WriteLine("Файл не открылся."); return false; }
  82. catch (Exception) { Console.WriteLine("Ошибка ввода-вывода."); return false; }
  83. }
  84. }
  85. static class Model
  86. {
  87.  
  88. public static List<Tuple<int, int>> ResList;
  89.  
  90. public static string[] vRes_s;//Модель набора ресурсов
  91. public static void Occupy(string cn)
  92. {
  93. if ((Convert.ToInt16(cn) > vRes_s.Length) | (Convert.ToInt16(cn) < 0)) throw new ResIdInvalid();
  94. if (vRes_s[Convert.ToInt16(cn) - 1] == "B")
  95. {
  96. ResIsBusy e = new ResIsBusy();
  97. e.Data.Add("resID", Convert.ToInt16(cn));
  98. throw e;
  99. }
  100. vRes_s[Convert.ToInt16(cn) - 1] = "B";
  101. }
  102. public static void Free(string cn)
  103. {
  104. if ((Convert.ToInt16(cn) > vRes_s.Length) | (Convert.ToInt16(cn) < 0)) throw new ResIdInvalid();
  105. if (vRes_s[Convert.ToInt16(cn) - 1] == "F") throw new ResWasFree();
  106. vRes_s[Convert.ToInt16(cn) - 1] = "F";
  107. }
  108. public static string Request()
  109. {
  110. for (int i = 0; i < vRes_s.Length; i++)
  111. {
  112. if (vRes_s[i] == "F") return Convert.ToString(i + 1);
  113. }
  114. throw new ResAreBusy(); ;
  115. }
  116. }
  117. class Program
  118. {
  119. static TimerCallback tm = new TimerCallback(TimeFreeRes);//Таймер для обработки заявок на ресурсе
  120. static Timer timer = new Timer(tm, null, Timeout.Infinite, Timeout.Infinite);//Вызов таймера для обработки заявок на ресурсе
  121. static bool timerFlag = false;
  122.  
  123. static void Main(string[] args)
  124. {
  125. string Command;
  126. while (!SetUp.On()) ;
  127. DateTime StartTime = DateTime.Now;
  128.  
  129. do
  130. { if (timerFlag)
  131. {
  132. Command = "Continue";
  133. continue;
  134. }
  135. File.WriteAllLines(SetUp.Path, Model.vRes_s);//сохранение модели
  136. Console.WriteLine("Введите команду:");
  137. Command = Console.ReadLine();
  138. DateTime StopTime = DateTime.Now;
  139. timer.Change(Timeout.Infinite, Timeout.Infinite);
  140. Command = Command.ToUpper();
  141. try
  142. {
  143. if (Command == "REQUEST") Console.WriteLine(Model.Request());
  144. if (Command == "OCCUPY")
  145. {
  146. Console.WriteLine("Введите номер ресурса:");
  147. Model.Occupy(Console.ReadLine());
  148. Console.WriteLine("Ресурс стал занятым.");
  149. };
  150. if (Command == "FREE")
  151. {
  152. Console.WriteLine("Введите номер ресурса:");
  153. Model.Free(Console.ReadLine());
  154. Console.WriteLine("Ресурс освобождён.");
  155. };
  156. }
  157. catch (OverflowException) { Console.WriteLine("Такого ресурса нет."); }
  158. catch (FormatException) { Console.WriteLine("Такого ресурса нет."); }
  159. catch (ResIdInvalid) { Console.WriteLine("Такого ресурса нет."); }
  160. catch (ResWasFree) { Console.WriteLine("Ресурс был свободен."); }
  161. catch (ResAreBusy) { Console.WriteLine("Все ресурсы заняты."); }
  162. catch (ResIsBusy e)
  163. {
  164. while (true)
  165. {
  166. Console.WriteLine("Ресурс уже занят. Ожидать его освобождения? Y/N?");
  167. string answer = Console.ReadLine();
  168. if (answer.ToUpper() == "Y")
  169. {
  170. int waitTime;
  171. while (true)
  172. {
  173. Console.WriteLine("Введите время ожидания.");
  174. try
  175. {
  176. waitTime = Convert.ToInt16(Console.ReadLine());
  177. break;
  178. }
  179. catch
  180. {
  181. Console.WriteLine("Неверный ввод, попробуйте снова.");
  182. }
  183. }
  184. TimeSpan elapsedTime = StopTime.Subtract(StartTime);
  185. for (int i = 0; i < Model.ResList.Count; i++)
  186. {
  187. Model.ResList[i] = new Tuple<int, int>(Model.ResList[i].Item1, Model.ResList[i].Item2 - (elapsedTime.Seconds));
  188. }
  189. Model.ResList.Add(new Tuple<int, int>(Convert.ToInt16(e.Data["resID"]), waitTime));
  190. Console.WriteLine("Запрос на ресурс {0} успешно добавлен в очередь.", Convert.ToInt16(e.Data["resID"]));
  191. Model.ResList.Sort(
  192. (t1, t2) =>
  193. {
  194. return t1.Item2.CompareTo(t2.Item2);
  195. });
  196. break;
  197. }
  198. else if (answer.ToUpper() == "N")
  199. break;
  200. else
  201. Console.WriteLine("Введите ответ снова.");
  202. }
  203. }
  204. if (Model.ResList.Count() == 0)
  205. timer.Change(Timeout.Infinite, Timeout.Infinite);
  206. else if (Model.ResList.Count() == 1)
  207. {
  208. timer.Change(Model.ResList[0].Item2 * 1000, Model.ResList[0].Item2 * 1000);
  209. StartTime = DateTime.Now;
  210. }
  211. else
  212. {
  213. for (int i = 0; i < Model.ResList.Count; i++)
  214. {
  215. Console.WriteLine("{0}",Model.ResList[i]);
  216. }
  217. timer.Change(Model.ResList[0].Item2 * 1000, Model.ResList[0].Item2 * 1000);
  218. StartTime = DateTime.Now;
  219. }
  220. }
  221. while (Command != "");
  222. }
  223.  
  224. static void TimeFreeRes(object obj)
  225. {
  226. timerFlag = true;
  227. timer.Change(Timeout.Infinite, Timeout.Infinite);
  228. if (Model.vRes_s[Model.ResList[0].Item1 - 1] == "B") //((Model.ResList.Count() >= 1) && (Model.vRes_s[Model.ResList[0].Item1-1] == "B"))
  229. {
  230. while (true)
  231. {
  232. Console.WriteLine("Ресурс {0} все еще занят. Ожидать его освобождения далее? Y/N?", Model.ResList[0].Item1);
  233. string answer = Console.ReadLine();
  234. if (answer.ToUpper() == "Y")
  235. {
  236. int waitTime;
  237. while (true)
  238. {
  239. Console.WriteLine("Введите время ожидания.");
  240. try
  241. {
  242. waitTime = Convert.ToInt16(Console.ReadLine());
  243. break;
  244. }
  245. catch
  246. {
  247. Console.WriteLine("Неверный ввод, попробуйте снова.");
  248. }
  249. }
  250. Model.ResList.Add(new Tuple<int, int>(Model.ResList[0].Item1, waitTime));
  251. Console.WriteLine("Запрос на ресурс {0} успешно продлен.", (Model.ResList[0].Item1));
  252. Model.ResList.RemoveAt(0);
  253. Model.ResList.Sort(
  254. (t1, t2) =>
  255. {
  256. return t1.Item2.CompareTo(t2.Item2);
  257. });
  258. break;
  259. }
  260. else if (answer.ToUpper() == "N")
  261. {
  262. Model.ResList.RemoveAt(0);
  263. Console.WriteLine("Запрос успешно удален.");
  264. if (Model.ResList.Count() >= 1)
  265. timer.Change(0, Model.ResList[0].Item2 * 1000);
  266. else
  267. timer.Change(Timeout.Infinite, Timeout.Infinite);
  268. break;
  269. }
  270. else
  271. Console.WriteLine("Введите ответ снова.");
  272. }
  273. }
  274. else //if (Model.ResList.Count() >= 1)
  275. {
  276.  
  277. Model.vRes_s[Model.ResList[0].Item1-1] = "B";
  278. Console.WriteLine("Ресурс {0} теперь занят.\nВведите команду:", Model.ResList[0].Item1);
  279. Model.ResList.RemoveAt(0);
  280. if (Model.ResList.Count() >= 1)
  281. timer.Change(0, Model.ResList[0].Item2 * 1000);
  282. else
  283. timer.Change(Timeout.Infinite, Timeout.Infinite);
  284. }
  285. timerFlag = false;
  286. }
  287. }
  288. }
  289.  
  290.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement