DarkDevourer

Lab PIAPS

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