BackgroundWorkerCollection.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Threading;
  5. using Terminal.Gui;
  6. namespace UICatalog.Scenarios;
  7. [ScenarioMetadata ("BackgroundWorker Collection", "A persisting multi Toplevel BackgroundWorker threading")]
  8. [ScenarioCategory ("Threading")]
  9. [ScenarioCategory ("Top Level Windows")]
  10. [ScenarioCategory ("Dialogs")]
  11. [ScenarioCategory ("Controls")]
  12. public class BackgroundWorkerCollection : Scenario
  13. {
  14. public override void Run () { Application.Run<OverlappedMain> (); }
  15. private class OverlappedMain : Toplevel
  16. {
  17. private readonly MenuBar _menu;
  18. private readonly WorkerApp _workerApp;
  19. private bool _canOpenWorkerApp;
  20. public OverlappedMain ()
  21. {
  22. Data = "OverlappedMain";
  23. IsOverlappedContainer = true;
  24. _workerApp = new WorkerApp { Visible = false };
  25. _menu = new MenuBar
  26. {
  27. Menus =
  28. [
  29. new MenuBarItem (
  30. "_Options",
  31. new MenuItem []
  32. {
  33. new (
  34. "_Run Worker",
  35. "",
  36. () => _workerApp.RunWorker (),
  37. null,
  38. null,
  39. KeyCode.CtrlMask | KeyCode.R
  40. ),
  41. new (
  42. "_Cancel Worker",
  43. "",
  44. () => _workerApp.CancelWorker (),
  45. null,
  46. null,
  47. KeyCode.CtrlMask | KeyCode.C
  48. ),
  49. null,
  50. new (
  51. "_Quit",
  52. "",
  53. () => Quit (),
  54. null,
  55. null,
  56. (KeyCode)Application.QuitKey
  57. )
  58. }
  59. ),
  60. new MenuBarItem ("_View", new MenuItem [] { }),
  61. new MenuBarItem ("_Window", new MenuItem [] { })
  62. ]
  63. };
  64. ;
  65. _menu.MenuOpening += Menu_MenuOpening;
  66. Add (_menu);
  67. var statusBar = new StatusBar (
  68. new []
  69. {
  70. new StatusItem (Application.QuitKey, $"{Application.QuitKey} to Quit", () => Quit ()),
  71. new StatusItem (
  72. KeyCode.CtrlMask | KeyCode.R,
  73. "~^R~ Run Worker",
  74. () => _workerApp.RunWorker ()
  75. ),
  76. new StatusItem (
  77. KeyCode.CtrlMask | KeyCode.C,
  78. "~^C~ Cancel Worker",
  79. () => _workerApp.CancelWorker ()
  80. )
  81. }
  82. );
  83. Add (statusBar);
  84. Activate += OverlappedMain_Activate;
  85. Deactivate += OverlappedMain_Deactivate;
  86. Closed += OverlappedMain_Closed;
  87. Application.Iteration += (s, a) =>
  88. {
  89. if (_canOpenWorkerApp && !_workerApp.Running && Application.OverlappedTop.Running)
  90. {
  91. Application.Run (_workerApp);
  92. }
  93. };
  94. }
  95. private void Menu_MenuOpening (object sender, MenuOpeningEventArgs menu)
  96. {
  97. if (!_canOpenWorkerApp)
  98. {
  99. _canOpenWorkerApp = true;
  100. return;
  101. }
  102. if (menu.CurrentMenu.Title == "_Window")
  103. {
  104. menu.NewMenuBarItem = OpenedWindows ();
  105. }
  106. else if (menu.CurrentMenu.Title == "_View")
  107. {
  108. menu.NewMenuBarItem = View ();
  109. }
  110. }
  111. private MenuBarItem OpenedWindows ()
  112. {
  113. var index = 1;
  114. List<MenuItem> menuItems = new ();
  115. List<Toplevel> sortedChildren = Application.OverlappedChildren;
  116. sortedChildren.Sort (new ToplevelComparer ());
  117. foreach (Toplevel top in sortedChildren)
  118. {
  119. if (top.Data.ToString () == "WorkerApp" && !top.Visible)
  120. {
  121. continue;
  122. }
  123. var item = new MenuItem ();
  124. item.Title = top is Window ? $"{index} {((Window)top).Title}" : $"{index} {top.Data}";
  125. index++;
  126. item.CheckType |= MenuItemCheckStyle.Checked;
  127. string topTitle = top is Window ? ((Window)top).Title : top.Data.ToString ();
  128. string itemTitle = item.Title.Substring (index.ToString ().Length + 1);
  129. if (top == Application.GetTopOverlappedChild () && topTitle == itemTitle)
  130. {
  131. item.Checked = true;
  132. }
  133. else
  134. {
  135. item.Checked = false;
  136. }
  137. item.Action += () => { Application.MoveToOverlappedChild (top); };
  138. menuItems.Add (item);
  139. }
  140. if (menuItems.Count == 0)
  141. {
  142. return new MenuBarItem ("_Window", "", null);
  143. }
  144. return new MenuBarItem ("_Window", new List<MenuItem []> { menuItems.ToArray () });
  145. }
  146. private void OverlappedMain_Activate (object sender, ToplevelEventArgs top) { _workerApp.WriteLog ($"{top.Toplevel.Data} activate."); }
  147. private void OverlappedMain_Closed (object sender, ToplevelEventArgs e)
  148. {
  149. _workerApp.Dispose ();
  150. Dispose ();
  151. }
  152. private void OverlappedMain_Deactivate (object sender, ToplevelEventArgs top) { _workerApp.WriteLog ($"{top.Toplevel.Data} deactivate."); }
  153. private void Quit () { RequestStop (); }
  154. private MenuBarItem View ()
  155. {
  156. List<MenuItem> menuItems = new ();
  157. var item = new MenuItem { Title = "WorkerApp", CheckType = MenuItemCheckStyle.Checked };
  158. Toplevel top = Application.OverlappedChildren?.Find (x => x.Data.ToString () == "WorkerApp");
  159. if (top != null)
  160. {
  161. item.Checked = top.Visible;
  162. }
  163. item.Action += () =>
  164. {
  165. Toplevel top = Application.OverlappedChildren.Find (x => x.Data.ToString () == "WorkerApp");
  166. item.Checked = top.Visible = (bool)!item.Checked;
  167. if (top.Visible)
  168. {
  169. Application.MoveToOverlappedChild (top);
  170. }
  171. else
  172. {
  173. Application.OverlappedTop.SetNeedsDisplay ();
  174. }
  175. };
  176. menuItems.Add (item);
  177. return new MenuBarItem (
  178. "_View",
  179. new List<MenuItem []> { menuItems.Count == 0 ? new MenuItem [] { } : menuItems.ToArray () }
  180. );
  181. }
  182. }
  183. private class Staging
  184. {
  185. public Staging (DateTime? startStaging, bool completed = false)
  186. {
  187. StartStaging = startStaging;
  188. Completed = completed;
  189. }
  190. public bool Completed { get; }
  191. public DateTime? StartStaging { get; }
  192. }
  193. private class StagingUIController : Window
  194. {
  195. private readonly Button _close;
  196. private readonly Label _label;
  197. private readonly ListView _listView;
  198. private readonly Button _start;
  199. public StagingUIController (Staging staging, List<string> list) : this ()
  200. {
  201. Staging = staging;
  202. _label.Text = "Work list:";
  203. _listView.SetSource (list);
  204. _start.Visible = false;
  205. Id = "";
  206. }
  207. public StagingUIController ()
  208. {
  209. X = Pos.Center ();
  210. Y = Pos.Center ();
  211. Width = Dim.Percent (85);
  212. Height = Dim.Percent (85);
  213. ColorScheme = Colors.ColorSchemes ["Dialog"];
  214. Title = "Run Worker";
  215. _label = new Label
  216. {
  217. X = Pos.Center (),
  218. Y = 1,
  219. ColorScheme = Colors.ColorSchemes ["Dialog"],
  220. Text = "Press start to do the work or close to quit."
  221. };
  222. Add (_label);
  223. _listView = new ListView { X = 0, Y = 2, Width = Dim.Fill (), Height = Dim.Fill (2) };
  224. Add (_listView);
  225. _start = new Button { Text = "Start", IsDefault = true, ClearOnVisibleFalse = false };
  226. _start.Accept += (s, e) =>
  227. {
  228. Staging = new Staging (DateTime.Now);
  229. RequestStop ();
  230. };
  231. Add (_start);
  232. _close = new Button { Text = "Close" };
  233. _close.Accept += OnReportClosed;
  234. Add (_close);
  235. KeyDown += (s, e) =>
  236. {
  237. if (e.KeyCode == KeyCode.Esc)
  238. {
  239. OnReportClosed (this, EventArgs.Empty);
  240. }
  241. };
  242. LayoutStarted += (s, e) =>
  243. {
  244. int btnsWidth = _start.Frame.Width + _close.Frame.Width + 2 - 1;
  245. int shiftLeft = Math.Max ((Viewport.Width - btnsWidth) / 2 - 2, 0);
  246. shiftLeft += _close.Frame.Width + 1;
  247. _close.X = Pos.AnchorEnd (shiftLeft);
  248. _close.Y = Pos.AnchorEnd (1);
  249. shiftLeft += _start.Frame.Width + 1;
  250. _start.X = Pos.AnchorEnd (shiftLeft);
  251. _start.Y = Pos.AnchorEnd (1);
  252. };
  253. }
  254. public Staging Staging { get; private set; }
  255. public event Action<StagingUIController> ReportClosed;
  256. public void Run () { Application.Run (this); }
  257. private void OnReportClosed (object sender, EventArgs e)
  258. {
  259. if (Staging?.StartStaging != null)
  260. {
  261. ReportClosed?.Invoke (this);
  262. }
  263. RequestStop ();
  264. }
  265. }
  266. private class WorkerApp : Toplevel
  267. {
  268. private readonly ListView _listLog;
  269. private readonly List<string> _log = [];
  270. private List<StagingUIController> _stagingsUi;
  271. private Dictionary<Staging, BackgroundWorker> _stagingWorkers;
  272. public WorkerApp ()
  273. {
  274. Data = "WorkerApp";
  275. Width = Dim.Percent (80);
  276. Height = Dim.Percent (50);
  277. ColorScheme = Colors.ColorSchemes ["Base"];
  278. var label = new Label { X = Pos.Center (), Y = 0, Text = "Worker collection Log" };
  279. Add (label);
  280. _listLog = new ListView
  281. {
  282. X = 0,
  283. Y = Pos.Bottom (label),
  284. Width = Dim.Fill (),
  285. Height = Dim.Fill (),
  286. Source = new ListWrapper (_log)
  287. };
  288. Add (_listLog);
  289. }
  290. public void CancelWorker ()
  291. {
  292. if (_stagingWorkers == null || _stagingWorkers.Count == 0)
  293. {
  294. WriteLog ($"Worker is not running at {DateTime.Now}!");
  295. return;
  296. }
  297. foreach (KeyValuePair<Staging, BackgroundWorker> sw in _stagingWorkers)
  298. {
  299. Staging key = sw.Key;
  300. BackgroundWorker value = sw.Value;
  301. if (!key.Completed)
  302. {
  303. value.CancelAsync ();
  304. }
  305. WriteLog (
  306. $"Worker {key.StartStaging}.{key.StartStaging:fff} is canceling at {DateTime.Now}!"
  307. );
  308. _stagingWorkers.Remove (sw.Key);
  309. }
  310. }
  311. public void RunWorker ()
  312. {
  313. var stagingUI = new StagingUIController { Modal = true };
  314. Staging staging = null;
  315. var worker = new BackgroundWorker { WorkerSupportsCancellation = true };
  316. worker.DoWork += (s, e) =>
  317. {
  318. List<string> stageResult = new ();
  319. for (var i = 0; i < 500; i++)
  320. {
  321. stageResult.Add (
  322. $"Worker {i} started at {DateTime.Now}"
  323. );
  324. e.Result = stageResult;
  325. Thread.Sleep (1);
  326. if (worker.CancellationPending)
  327. {
  328. e.Cancel = true;
  329. return;
  330. }
  331. }
  332. };
  333. worker.RunWorkerCompleted += (s, e) =>
  334. {
  335. if (e.Error != null)
  336. {
  337. // Failed
  338. WriteLog (
  339. $"Exception occurred {
  340. e.Error.Message
  341. } on Worker {
  342. staging.StartStaging
  343. }.{
  344. staging.StartStaging
  345. :fff} at {
  346. DateTime.Now
  347. }"
  348. );
  349. }
  350. else if (e.Cancelled)
  351. {
  352. // Canceled
  353. WriteLog (
  354. $"Worker {staging.StartStaging}.{staging.StartStaging:fff} was canceled at {DateTime.Now}!"
  355. );
  356. }
  357. else
  358. {
  359. // Passed
  360. WriteLog (
  361. $"Worker {staging.StartStaging}.{staging.StartStaging:fff} was completed at {DateTime.Now}."
  362. );
  363. Application.Refresh ();
  364. var stagingUI = new StagingUIController (staging, e.Result as List<string>)
  365. {
  366. Modal = false,
  367. Title =
  368. $"Worker started at {staging.StartStaging}.{staging.StartStaging:fff}",
  369. Data = $"{staging.StartStaging}.{staging.StartStaging:fff}"
  370. };
  371. stagingUI.ReportClosed += StagingUI_ReportClosed;
  372. if (_stagingsUi == null)
  373. {
  374. _stagingsUi = new List<StagingUIController> ();
  375. }
  376. _stagingsUi.Add (stagingUI);
  377. _stagingWorkers.Remove (staging);
  378. stagingUI.Run ();
  379. }
  380. };
  381. Application.Run (stagingUI);
  382. if (stagingUI.Staging != null && stagingUI.Staging.StartStaging != null)
  383. {
  384. staging = new Staging (stagingUI.Staging.StartStaging);
  385. WriteLog ($"Worker is started at {staging.StartStaging}.{staging.StartStaging:fff}");
  386. if (_stagingWorkers == null)
  387. {
  388. _stagingWorkers = new Dictionary<Staging, BackgroundWorker> ();
  389. }
  390. _stagingWorkers.Add (staging, worker);
  391. worker.RunWorkerAsync ();
  392. stagingUI.Dispose ();
  393. }
  394. }
  395. public void WriteLog (string msg)
  396. {
  397. _log.Add (msg);
  398. _listLog.MoveDown ();
  399. }
  400. private void StagingUI_ReportClosed (StagingUIController obj)
  401. {
  402. WriteLog ($"Report {obj.Staging.StartStaging}.{obj.Staging.StartStaging:fff} closed.");
  403. _stagingsUi.Remove (obj);
  404. }
  405. }
  406. }