Threading.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using Terminal.Gui;
  6. namespace UICatalog.Scenarios {
  7. [ScenarioMetadata (Name: "Threading", Description: "Demonstration of how to use threading in different ways")]
  8. [ScenarioCategory ("Threading")]
  9. public class Threading : Scenario {
  10. private Action _action;
  11. private Action _lambda;
  12. private EventHandler _handler;
  13. private Action _sync;
  14. private ListView _itemsList;
  15. private Button _btnActionCancel;
  16. List<string> log = new List<string> ();
  17. private ListView _logJob;
  18. public override void Setup ()
  19. {
  20. _action = LoadData;
  21. _lambda = async () => {
  22. _itemsList.Source = null;
  23. LogJob ("Loading task lambda");
  24. var items = await LoadDataAsync ();
  25. LogJob ("Returning from task lambda");
  26. _itemsList.SetSource (items);
  27. };
  28. _handler = async (s, e) => {
  29. _itemsList.Source = null;
  30. LogJob ("Loading task handler");
  31. var items = await LoadDataAsync ();
  32. LogJob ("Returning from task handler");
  33. _itemsList.SetSource (items);
  34. };
  35. _sync = () => {
  36. _itemsList.Source = null;
  37. LogJob ("Loading task synchronous");
  38. List<string> items = new List<string> () { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };
  39. LogJob ("Returning from task synchronous");
  40. _itemsList.SetSource (items);
  41. };
  42. _btnActionCancel = new Button (1, 1, "Cancelable Load Items");
  43. _btnActionCancel.Clicked += () => Application.MainLoop.Invoke (CallLoadItemsAsync);
  44. Win.Add (new Label ("Data Items:") {
  45. X = Pos.X (_btnActionCancel),
  46. Y = Pos.Y (_btnActionCancel) + 4,
  47. });
  48. _itemsList = new ListView {
  49. X = Pos.X (_btnActionCancel),
  50. Y = Pos.Y (_btnActionCancel) + 6,
  51. Width = 10,
  52. Height = 10,
  53. ColorScheme = Colors.TopLevel
  54. };
  55. Win.Add (new Label ("Task Logs:") {
  56. X = Pos.Right (_itemsList) + 10,
  57. Y = Pos.Y (_btnActionCancel) + 4,
  58. });
  59. _logJob = new ListView (log) {
  60. X = Pos.Right (_itemsList) + 10,
  61. Y = Pos.Y (_itemsList),
  62. Width = 50,
  63. Height = Dim.Fill (),
  64. ColorScheme = Colors.TopLevel
  65. };
  66. var text = new TextField (1, 3, 100, "Type anything after press the button");
  67. var _btnAction = new Button (80, 10, "Load Data Action");
  68. _btnAction.Clicked += () => _action.Invoke ();
  69. var _btnLambda = new Button (80, 12, "Load Data Lambda");
  70. _btnLambda.Clicked += () => _lambda.Invoke ();
  71. var _btnHandler = new Button (80, 14, "Load Data Handler");
  72. _btnHandler.Clicked += () => _handler.Invoke (null, new EventArgs ());
  73. var _btnSync = new Button (80, 16, "Load Data Synchronous");
  74. _btnSync.Clicked += () => _sync.Invoke ();
  75. var _btnMethod = new Button (80, 18, "Load Data Method");
  76. _btnMethod.Clicked += async () => await MethodAsync ();
  77. var _btnClearData = new Button (80, 20, "Clear Data");
  78. _btnClearData.Clicked += () => { _itemsList.Source = null; LogJob ("Cleaning Data"); };
  79. var _btnQuit = new Button (80, 22, "Quit");
  80. _btnQuit.Clicked += () => Application.RequestStop ();
  81. Win.Add (_itemsList, _btnActionCancel, _logJob, text, _btnAction, _btnLambda, _btnHandler, _btnSync, _btnMethod, _btnClearData, _btnQuit);
  82. void Top_Loaded ()
  83. {
  84. _btnActionCancel.SetFocus ();
  85. Application.Top.Loaded -= Top_Loaded;
  86. }
  87. Application.Top.Loaded += Top_Loaded;
  88. }
  89. private async void LoadData ()
  90. {
  91. _itemsList.Source = null;
  92. LogJob ("Loading task");
  93. var items = await LoadDataAsync ();
  94. LogJob ("Returning from task");
  95. _itemsList.SetSource (items);
  96. }
  97. private void LogJob (string job)
  98. {
  99. log.Add (job);
  100. _logJob.MoveDown ();
  101. }
  102. private async Task<List<string>> LoadDataAsync ()
  103. {
  104. _itemsList.Source = null;
  105. LogJob ("Starting delay");
  106. await Task.Delay (3000);
  107. LogJob ("Finished delay");
  108. return new List<string> () { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };
  109. }
  110. private async Task MethodAsync ()
  111. {
  112. _itemsList.Source = null;
  113. LogJob ("Loading task method");
  114. List<string> items = new List<string> () { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };
  115. await Task.Delay (3000);
  116. LogJob ("Returning from task method");
  117. await _itemsList.SetSourceAsync (items);
  118. _itemsList.SetNeedsDisplay ();
  119. }
  120. private CancellationTokenSource cancellationTokenSource;
  121. private async void CallLoadItemsAsync ()
  122. {
  123. cancellationTokenSource = new CancellationTokenSource ();
  124. _itemsList.Source = null;
  125. LogJob ($"Clicked the button");
  126. if (_btnActionCancel.Text == "Cancel") {
  127. _btnActionCancel.Text = "Cancelable Load Items";
  128. cancellationTokenSource.Cancel ();
  129. } else
  130. _btnActionCancel.Text = "Cancel";
  131. try {
  132. if (cancellationTokenSource.Token.IsCancellationRequested)
  133. cancellationTokenSource.Token.ThrowIfCancellationRequested ();
  134. LogJob ($"Calling task Thread:{Thread.CurrentThread.ManagedThreadId} {DateTime.Now}");
  135. var items = await Task.Run (LoadItemsAsync, cancellationTokenSource.Token);
  136. if (!cancellationTokenSource.IsCancellationRequested) {
  137. LogJob ($"Returned from task Thread:{Thread.CurrentThread.ManagedThreadId} {DateTime.Now}");
  138. _itemsList.SetSource (items);
  139. LogJob ($"Finished populate list view Thread:{Thread.CurrentThread.ManagedThreadId} {DateTime.Now}");
  140. _btnActionCancel.Text = "Cancelable Load Items";
  141. } else {
  142. LogJob ("Task was canceled!");
  143. }
  144. } catch (OperationCanceledException ex) {
  145. LogJob (ex.Message);
  146. }
  147. }
  148. private async Task<List<string>> LoadItemsAsync ()
  149. {
  150. // Do something that takes lot of times.
  151. LogJob ($"Starting delay Thread:{Thread.CurrentThread.ManagedThreadId} {DateTime.Now}");
  152. await Task.Delay (5000);
  153. LogJob ($"Finished delay Thread:{Thread.CurrentThread.ManagedThreadId} {DateTime.Now}");
  154. return new List<string> () { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };
  155. }
  156. }
  157. }