BackgroundWorkerCollection.cs 19 KB

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