DarkDevourer

Lab1 V 2

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