Advertisement
DarkDevourer

L1 Last

May 12th, 2021
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.25 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 Thread mainMenu;
  120.  
  121. static DateTime StartTime = DateTime.Now;
  122. static DateTime StopTime;
  123. static TimerCallback tm = new TimerCallback(TimeFreeRes);//Таймер для обработки заявок на ресурсе
  124. static Timer timer = new Timer(tm, null, Timeout.Infinite, Timeout.Infinite);//Вызов таймера для обработки заявок на ресурсе
  125.  
  126. static void Main(string[] args)
  127. {
  128. while (!SetUp.On()) ;
  129.  
  130. mainMenu = new Thread(Menu);
  131. mainMenu.Start();
  132. }
  133. public static void Menu()
  134. {
  135. string Command;
  136.  
  137. do
  138. {
  139. Command = "Continue";
  140. File.WriteAllLines(SetUp.Path, Model.vRes_s);//сохранение модели
  141. Console.WriteLine("Введите команду:");
  142. Command = Console.ReadLine();
  143. StopTime = DateTime.Now;
  144. timer.Change(Timeout.Infinite, Timeout.Infinite);
  145. Command = Command.ToUpper();
  146. try
  147. {
  148. if (Command == "REQUEST") Console.WriteLine(Model.Request());
  149. if (Command == "OCCUPY")
  150. {
  151. Console.WriteLine("Введите номер ресурса:");
  152. Model.Occupy(Console.ReadLine());
  153. Console.WriteLine("Ресурс стал занятым.");
  154. };
  155. if (Command == "FREE")
  156. {
  157. Console.WriteLine("Введите номер ресурса:");
  158. Model.Free(Console.ReadLine());
  159. Console.WriteLine("Ресурс освобождён.");
  160. };
  161. }
  162. catch (OverflowException) { Console.WriteLine("Такого ресурса нет."); }
  163. catch (FormatException) { Console.WriteLine("Такого ресурса нет."); }
  164. catch (ResIdInvalid) { Console.WriteLine("Такого ресурса нет."); }
  165. catch (ResWasFree) { Console.WriteLine("Ресурс был свободен."); }
  166. catch (ResAreBusy) { Console.WriteLine("Все ресурсы заняты."); }
  167. catch (ResIsBusy e)
  168. {
  169. while (true)
  170. {
  171. Console.WriteLine("Ресурс уже занят. Ожидать его освобождения? Y/N?");
  172. string answer = Console.ReadLine();
  173. if (answer.ToUpper() == "Y")
  174. {
  175. int waitTime;
  176. while (true)
  177. {
  178. Console.WriteLine("Введите время ожидания.");
  179. try
  180. {
  181. waitTime = Convert.ToInt16(Console.ReadLine());
  182. break;
  183. }
  184. catch
  185. {
  186. Console.WriteLine("Неверный ввод, попробуйте снова.");
  187. }
  188. }
  189. ListTimeChange();
  190. Model.ResList.Add(new Tuple<int, int>(Convert.ToInt16(e.Data["resID"]), waitTime));
  191. Console.WriteLine("Запрос на ресурс {0} успешно добавлен в очередь.", Convert.ToInt16(e.Data["resID"]));
  192. SortList();
  193. break;
  194. }
  195. else if (answer.ToUpper() == "N")
  196. break;
  197. else
  198. Console.WriteLine("Введите ответ снова.");
  199. }
  200. }
  201. if (Model.ResList.Count() == 0)
  202. timer.Change(Timeout.Infinite, Timeout.Infinite);
  203. else
  204. {
  205. PrintList();
  206. timer.Change(Model.ResList[0].Item2 * 1000, Model.ResList[0].Item2 * 1000);
  207. StartTime = DateTime.Now;
  208. }
  209. }
  210.  
  211. while (Command != "");
  212. }
  213.  
  214. static void TimeFreeRes(object obj)
  215. {
  216. StopTime = DateTime.Now;
  217. mainMenu.Suspend();
  218. timer.Change(Timeout.Infinite, Timeout.Infinite);
  219. using (var s = Console.OpenStandardInput())
  220. using (var sr = new StreamReader(s))
  221. if (Model.vRes_s[Model.ResList[0].Item1 - 1] == "B")
  222. {
  223. while (true)
  224. {
  225. Console.WriteLine("Ресурс {0} все еще занят. Ожидать его освобождения далее? Y/N?", Model.ResList[0].Item1);
  226. string answer = sr.ReadLine();
  227. if (answer.ToUpper() == "Y")
  228. {
  229. int waitTime;
  230. while (true)
  231. {
  232. Console.WriteLine("Введите время ожидания.");
  233. try
  234. {
  235. waitTime = Convert.ToInt16(sr.ReadLine());
  236. break;
  237. }
  238. catch
  239. {
  240. Console.WriteLine("Неверный ввод, попробуйте снова.");
  241. }
  242. }
  243. ListTimeChange();
  244. Model.ResList.Add(new Tuple<int, int>(Model.ResList[0].Item1, waitTime));
  245. Console.WriteLine("Запрос на ресурс {0} успешно продлен.", (Model.ResList[0].Item1));
  246. Model.ResList.RemoveAt(0);
  247. SortList();
  248. PrintList();
  249. Console.WriteLine("Введите команду:");
  250. timer.Change(Model.ResList[0].Item2 * 1000, Model.ResList[0].Item2 * 1000);
  251. break;
  252. }
  253. else if (answer.ToUpper() == "N")
  254. {
  255. Model.ResList.RemoveAt(0);
  256. Console.WriteLine("Запрос успешно удален.");
  257. ListTimeChange();
  258. if (Model.ResList.Count() > 0)
  259. timer.Change(Model.ResList[0].Item2 * 1000, Model.ResList[0].Item2 * 1000);
  260. else
  261. timer.Change(Timeout.Infinite, Timeout.Infinite);
  262. PrintList();
  263. Console.WriteLine("Введите команду:");
  264. break;
  265. }
  266. else
  267. Console.WriteLine("Введите ответ снова.");
  268. }
  269. }
  270. else
  271. {
  272. Model.Occupy(Convert.ToString(Model.ResList[0].Item1 - 1));
  273. Console.WriteLine("Ресурс {0} теперь занят.", Model.ResList[0].Item1);
  274. Model.ResList.RemoveAt(0);
  275. ListTimeChange();
  276. PrintList();
  277. Console.WriteLine("Введите команду:");
  278. if (Model.ResList.Count() >= 1)
  279. timer.Change(Model.ResList[0].Item2 * 1000, Model.ResList[0].Item2 * 1000);
  280. else
  281. timer.Change(Timeout.Infinite, Timeout.Infinite);
  282. }
  283. StartTime = DateTime.Now;
  284. mainMenu.Resume();
  285. }
  286.  
  287. private static void SortList()
  288. {
  289. Model.ResList.Sort((t1, t2) => { return t1.Item2.CompareTo(t2.Item2); });
  290. }
  291.  
  292. private static void PrintList()
  293. {
  294. for (int i = 0; i < Model.ResList.Count; i++)
  295. {
  296. Console.WriteLine("{0}", Model.ResList[i]);
  297. }
  298. }
  299.  
  300. private static void ListTimeChange()
  301. {
  302. TimeSpan elapsedTime = StopTime.Subtract(StartTime);
  303. for (int i = 0; i < Model.ResList.Count; i++)
  304. {
  305. Model.ResList[i] = new Tuple<int, int>(Model.ResList[i].Item1, Model.ResList[i].Item2 - (elapsedTime.Seconds));
  306. }
  307. }
  308. }
  309. }
  310.  
  311.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement