BackgroundWorkerCollection.cs 19 KB

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