BackgroundWorkerCollection.cs 19 KB

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