Advertisement
DarkDevourer

Lab1 New

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