MainLoopTests.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Runtime.InteropServices.ComTypes;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Terminal.Gui;
  10. using Xunit;
  11. using Xunit.Sdk;
  12. // Alias Console to MockConsole so we don't accidentally use Console
  13. using Console = Terminal.Gui.FakeConsole;
  14. namespace Terminal.Gui.Core {
  15. public class MainLoopTests {
  16. [Fact]
  17. public void Constructor_Setups_Driver ()
  18. {
  19. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  20. Assert.NotNull (ml.Driver);
  21. }
  22. // Idle Handler tests
  23. [Fact]
  24. public void AddIdle_Adds_And_Removes ()
  25. {
  26. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  27. Func<bool> fnTrue = () => true;
  28. Func<bool> fnFalse = () => false;
  29. ml.AddIdle (fnTrue);
  30. ml.AddIdle (fnFalse);
  31. Assert.Equal (2, ml.IdleHandlers.Count);
  32. Assert.Equal (fnTrue, ml.IdleHandlers [0]);
  33. Assert.NotEqual (fnFalse, ml.IdleHandlers [0]);
  34. Assert.True (ml.RemoveIdle (fnTrue));
  35. Assert.Single (ml.IdleHandlers);
  36. // BUGBUG: This doesn't throw or indicate an error. Ideally RemoveIdle would either
  37. // throw an exception in this case, or return an error.
  38. // No. Only need to return a boolean.
  39. Assert.False (ml.RemoveIdle (fnTrue));
  40. Assert.True (ml.RemoveIdle (fnFalse));
  41. // BUGBUG: This doesn't throw an exception or indicate an error. Ideally RemoveIdle would either
  42. // throw an exception in this case, or return an error.
  43. // No. Only need to return a boolean.
  44. Assert.False (ml.RemoveIdle (fnFalse));
  45. // Add again, but with dupe
  46. ml.AddIdle (fnTrue);
  47. ml.AddIdle (fnTrue);
  48. Assert.Equal (2, ml.IdleHandlers.Count);
  49. Assert.Equal (fnTrue, ml.IdleHandlers [0]);
  50. Assert.True (ml.IdleHandlers [0] ());
  51. Assert.Equal (fnTrue, ml.IdleHandlers [1]);
  52. Assert.True (ml.IdleHandlers [1] ());
  53. Assert.True (ml.RemoveIdle (fnTrue));
  54. Assert.Single (ml.IdleHandlers);
  55. Assert.Equal (fnTrue, ml.IdleHandlers [0]);
  56. Assert.NotEqual (fnFalse, ml.IdleHandlers [0]);
  57. Assert.True (ml.RemoveIdle (fnTrue));
  58. Assert.Empty (ml.IdleHandlers);
  59. // BUGBUG: This doesn't throw an exception or indicate an error. Ideally RemoveIdle would either
  60. // throw an exception in this case, or return an error.
  61. // No. Only need to return a boolean.
  62. Assert.False (ml.RemoveIdle (fnTrue));
  63. }
  64. [Fact]
  65. public void AddIdle_Function_GetsCalled_OnIteration ()
  66. {
  67. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  68. var functionCalled = 0;
  69. Func<bool> fn = () => {
  70. functionCalled++;
  71. return true;
  72. };
  73. ml.AddIdle (fn);
  74. ml.MainIteration ();
  75. Assert.Equal (1, functionCalled);
  76. }
  77. [Fact]
  78. public void RemoveIdle_Function_NotCalled ()
  79. {
  80. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  81. var functionCalled = 0;
  82. Func<bool> fn = () => {
  83. functionCalled++;
  84. return true;
  85. };
  86. Assert.False (ml.RemoveIdle (fn));
  87. ml.MainIteration ();
  88. Assert.Equal (0, functionCalled);
  89. }
  90. [Fact]
  91. public void AddThenRemoveIdle_Function_NotCalled ()
  92. {
  93. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  94. var functionCalled = 0;
  95. Func<bool> fn = () => {
  96. functionCalled++;
  97. return true;
  98. };
  99. ml.AddIdle (fn);
  100. Assert.True (ml.RemoveIdle (fn));
  101. ml.MainIteration ();
  102. Assert.Equal (0, functionCalled);
  103. }
  104. [Fact]
  105. public void AddTwice_Function_CalledTwice ()
  106. {
  107. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  108. var functionCalled = 0;
  109. Func<bool> fn = () => {
  110. functionCalled++;
  111. return true;
  112. };
  113. ml.AddIdle (fn);
  114. ml.AddIdle (fn);
  115. ml.MainIteration ();
  116. Assert.Equal (2, functionCalled);
  117. Assert.Equal (2, ml.IdleHandlers.Count);
  118. functionCalled = 0;
  119. Assert.True (ml.RemoveIdle (fn));
  120. Assert.Single (ml.IdleHandlers);
  121. ml.MainIteration ();
  122. Assert.Equal (1, functionCalled);
  123. functionCalled = 0;
  124. Assert.True (ml.RemoveIdle (fn));
  125. Assert.Empty (ml.IdleHandlers);
  126. ml.MainIteration ();
  127. Assert.Equal (0, functionCalled);
  128. Assert.False (ml.RemoveIdle (fn));
  129. }
  130. [Fact]
  131. public void False_Idle_Stops_It_Being_Called_Again ()
  132. {
  133. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  134. var functionCalled = 0;
  135. Func<bool> fn1 = () => {
  136. functionCalled++;
  137. if (functionCalled == 10) {
  138. return false;
  139. }
  140. return true;
  141. };
  142. // Force stop if 20 iterations
  143. var stopCount = 0;
  144. Func<bool> fnStop = () => {
  145. stopCount++;
  146. if (stopCount == 20) {
  147. ml.Stop ();
  148. }
  149. return true;
  150. };
  151. ml.AddIdle (fnStop);
  152. ml.AddIdle (fn1);
  153. ml.Run ();
  154. Assert.True (ml.RemoveIdle (fnStop));
  155. Assert.False (ml.RemoveIdle (fn1));
  156. Assert.Equal (10, functionCalled);
  157. Assert.Equal (20, stopCount);
  158. }
  159. [Fact]
  160. public void AddIdle_Twice_Returns_False_Called_Twice ()
  161. {
  162. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  163. var functionCalled = 0;
  164. Func<bool> fn1 = () => {
  165. functionCalled++;
  166. return false;
  167. };
  168. // Force stop if 10 iterations
  169. var stopCount = 0;
  170. Func<bool> fnStop = () => {
  171. stopCount++;
  172. if (stopCount == 10) {
  173. ml.Stop ();
  174. }
  175. return true;
  176. };
  177. ml.AddIdle (fnStop);
  178. ml.AddIdle (fn1);
  179. ml.AddIdle (fn1);
  180. ml.Run ();
  181. Assert.True (ml.RemoveIdle (fnStop));
  182. Assert.False (ml.RemoveIdle (fn1));
  183. Assert.False (ml.RemoveIdle (fn1));
  184. Assert.Equal (2, functionCalled);
  185. }
  186. [Fact]
  187. public void Run_Runs_Idle_Stop_Stops_Idle ()
  188. {
  189. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  190. var functionCalled = 0;
  191. Func<bool> fn = () => {
  192. functionCalled++;
  193. if (functionCalled == 10) {
  194. ml.Stop ();
  195. }
  196. return true;
  197. };
  198. ml.AddIdle (fn);
  199. ml.Run ();
  200. Assert.True (ml.RemoveIdle (fn));
  201. Assert.Equal (10, functionCalled);
  202. }
  203. // Timeout Handler Tests
  204. [Fact]
  205. public void AddTimer_Adds_Removes_NoFaults ()
  206. {
  207. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  208. var ms = 100;
  209. var callbackCount = 0;
  210. Func<MainLoop, bool> callback = (MainLoop loop) => {
  211. callbackCount++;
  212. return true;
  213. };
  214. var token = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback);
  215. Assert.True (ml.RemoveTimeout (token));
  216. // BUGBUG: This should probably fault?
  217. // Must return a boolean.
  218. Assert.False (ml.RemoveTimeout (token));
  219. }
  220. [Fact]
  221. public void AddTimer_Run_Called ()
  222. {
  223. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  224. var ms = 100;
  225. var callbackCount = 0;
  226. Func<MainLoop, bool> callback = (MainLoop loop) => {
  227. callbackCount++;
  228. ml.Stop ();
  229. return true;
  230. };
  231. var token = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback);
  232. ml.Run ();
  233. Assert.True (ml.RemoveTimeout (token));
  234. Assert.Equal (1, callbackCount);
  235. }
  236. [Fact]
  237. public async Task AddTimer_Duplicate_Keys_Not_Allowed ()
  238. {
  239. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  240. const int ms = 100;
  241. object token1 = null, token2 = null;
  242. var callbackCount = 0;
  243. Func<MainLoop, bool> callback = (MainLoop loop) => {
  244. callbackCount++;
  245. if (callbackCount == 2) {
  246. ml.Stop ();
  247. }
  248. return true;
  249. };
  250. var task1 = new Task (() => token1 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback));
  251. var task2 = new Task (() => token2 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback));
  252. Assert.Null (token1);
  253. Assert.Null (token2);
  254. task1.Start ();
  255. task2.Start ();
  256. ml.Run ();
  257. Assert.NotNull (token1);
  258. Assert.NotNull (token2);
  259. await Task.WhenAll (task1, task2);
  260. Assert.True (ml.RemoveTimeout (token1));
  261. Assert.True (ml.RemoveTimeout (token2));
  262. Assert.Equal (2, callbackCount);
  263. }
  264. [Fact]
  265. public void AddTimer_In_Parallel_Wont_Throw ()
  266. {
  267. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  268. const int ms = 100;
  269. object token1 = null, token2 = null;
  270. var callbackCount = 0;
  271. Func<MainLoop, bool> callback = (MainLoop loop) => {
  272. callbackCount++;
  273. if (callbackCount == 2) {
  274. ml.Stop ();
  275. }
  276. return true;
  277. };
  278. Parallel.Invoke (
  279. () => token1 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback),
  280. () => token2 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback)
  281. );
  282. ml.Run ();
  283. Assert.NotNull (token1);
  284. Assert.NotNull (token2);
  285. Assert.True (ml.RemoveTimeout (token1));
  286. Assert.True (ml.RemoveTimeout (token2));
  287. Assert.Equal (2, callbackCount);
  288. }
  289. class MillisecondTolerance : IEqualityComparer<TimeSpan> {
  290. int _tolerance = 0;
  291. public MillisecondTolerance (int tolerance) { _tolerance = tolerance; }
  292. public bool Equals (TimeSpan x, TimeSpan y) => Math.Abs (x.Milliseconds - y.Milliseconds) <= _tolerance;
  293. public int GetHashCode (TimeSpan obj) => obj.GetHashCode ();
  294. }
  295. [Fact]
  296. public void AddTimer_Run_CalledAtApproximatelyRightTime ()
  297. {
  298. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  299. var ms = TimeSpan.FromMilliseconds (50);
  300. var watch = new System.Diagnostics.Stopwatch ();
  301. var callbackCount = 0;
  302. Func<MainLoop, bool> callback = (MainLoop loop) => {
  303. watch.Stop ();
  304. callbackCount++;
  305. ml.Stop ();
  306. return true;
  307. };
  308. var token = ml.AddTimeout (ms, callback);
  309. watch.Start ();
  310. ml.Run ();
  311. // +/- 100ms should be good enuf
  312. // https://github.com/xunit/assert.xunit/pull/25
  313. Assert.Equal<TimeSpan> (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
  314. Assert.True (ml.RemoveTimeout (token));
  315. Assert.Equal (1, callbackCount);
  316. }
  317. [Fact]
  318. public void AddTimer_Run_CalledTwiceApproximatelyRightTime ()
  319. {
  320. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  321. var ms = TimeSpan.FromMilliseconds (50);
  322. var watch = new System.Diagnostics.Stopwatch ();
  323. var callbackCount = 0;
  324. Func<MainLoop, bool> callback = (MainLoop loop) => {
  325. callbackCount++;
  326. if (callbackCount == 2) {
  327. watch.Stop ();
  328. ml.Stop ();
  329. }
  330. return true;
  331. };
  332. var token = ml.AddTimeout (ms, callback);
  333. watch.Start ();
  334. ml.Run ();
  335. // +/- 100ms should be good enuf
  336. // https://github.com/xunit/assert.xunit/pull/25
  337. Assert.Equal<TimeSpan> (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
  338. Assert.True (ml.RemoveTimeout (token));
  339. Assert.Equal (2, callbackCount);
  340. }
  341. [Fact]
  342. public void AddTimer_Remove_NotCalled ()
  343. {
  344. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  345. var ms = TimeSpan.FromMilliseconds (50);
  346. // Force stop if 10 iterations
  347. var stopCount = 0;
  348. Func<bool> fnStop = () => {
  349. stopCount++;
  350. if (stopCount == 10) {
  351. ml.Stop ();
  352. }
  353. return true;
  354. };
  355. ml.AddIdle (fnStop);
  356. var callbackCount = 0;
  357. Func<MainLoop, bool> callback = (MainLoop loop) => {
  358. callbackCount++;
  359. return true;
  360. };
  361. var token = ml.AddTimeout (ms, callback);
  362. Assert.True (ml.RemoveTimeout (token));
  363. ml.Run ();
  364. Assert.Equal (0, callbackCount);
  365. }
  366. [Fact]
  367. public void AddTimer_ReturnFalse_StopsBeingCalled ()
  368. {
  369. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  370. var ms = TimeSpan.FromMilliseconds (50);
  371. // Force stop if 10 iterations
  372. var stopCount = 0;
  373. Func<bool> fnStop = () => {
  374. Thread.Sleep (10); // Sleep to enable timer to fire
  375. stopCount++;
  376. if (stopCount == 10) {
  377. ml.Stop ();
  378. }
  379. return true;
  380. };
  381. ml.AddIdle (fnStop);
  382. var callbackCount = 0;
  383. Func<MainLoop, bool> callback = (MainLoop loop) => {
  384. callbackCount++;
  385. return false;
  386. };
  387. var token = ml.AddTimeout (ms, callback);
  388. ml.Run ();
  389. Assert.Equal (1, callbackCount);
  390. Assert.Equal (10, stopCount);
  391. Assert.False (ml.RemoveTimeout (token));
  392. }
  393. // Invoke Tests
  394. // TODO: Test with threading scenarios
  395. [Fact]
  396. public void Invoke_Adds_Idle ()
  397. {
  398. var ml = new MainLoop (new FakeMainLoop (() => FakeConsole.ReadKey (true)));
  399. var actionCalled = 0;
  400. ml.Invoke (() => { actionCalled++; });
  401. ml.MainIteration ();
  402. Assert.Equal (1, actionCalled);
  403. }
  404. [Fact]
  405. public void Internal_Tests ()
  406. {
  407. var testMainloop = new TestMainloop ();
  408. var mainloop = new MainLoop (testMainloop);
  409. Assert.Empty (mainloop.timeouts);
  410. Assert.Empty (mainloop.idleHandlers);
  411. Assert.NotNull (new MainLoop.Timeout () {
  412. Span = new TimeSpan (),
  413. Callback = (_) => true
  414. });
  415. }
  416. private class TestMainloop : IMainLoopDriver {
  417. private MainLoop mainLoop;
  418. public bool EventsPending (bool wait)
  419. {
  420. throw new NotImplementedException ();
  421. }
  422. public void MainIteration ()
  423. {
  424. throw new NotImplementedException ();
  425. }
  426. public void Setup (MainLoop mainLoop)
  427. {
  428. this.mainLoop = mainLoop;
  429. }
  430. public void Wakeup ()
  431. {
  432. throw new NotImplementedException ();
  433. }
  434. }
  435. // TODO: EventsPending tests
  436. // - wait = true
  437. // - wait = false
  438. // TODO: Add IMainLoop tests
  439. volatile static int tbCounter = 0;
  440. static ManualResetEventSlim _wakeUp = new ManualResetEventSlim (false);
  441. private static void Launch (Random r, TextField tf, int target)
  442. {
  443. Task.Run (() => {
  444. Thread.Sleep (r.Next (2, 4));
  445. Application.MainLoop.Invoke (() => {
  446. tf.Text = $"index{r.Next ()}";
  447. Interlocked.Increment (ref tbCounter);
  448. if (target == tbCounter) {
  449. // On last increment wake up the check
  450. _wakeUp.Set ();
  451. }
  452. });
  453. });
  454. }
  455. private static void RunTest (Random r, TextField tf, int numPasses, int numIncrements, int pollMs)
  456. {
  457. for (int j = 0; j < numPasses; j++) {
  458. _wakeUp.Reset ();
  459. for (var i = 0; i < numIncrements; i++) {
  460. Launch (r, tf, (j + 1) * numIncrements);
  461. }
  462. while (tbCounter != (j + 1) * numIncrements) // Wait for tbCounter to reach expected value
  463. {
  464. var tbNow = tbCounter;
  465. _wakeUp.Wait (pollMs);
  466. if (tbCounter == tbNow) {
  467. // No change after wait: Idle handlers added via Application.MainLoop.Invoke have gone missing
  468. Application.MainLoop.Invoke (() => Application.RequestStop ());
  469. throw new TimeoutException (
  470. $"Timeout: Increment lost. tbCounter ({tbCounter}) didn't " +
  471. $"change after waiting {pollMs} ms. Failed to reach {(j + 1) * numIncrements} on pass {j + 1}");
  472. }
  473. };
  474. }
  475. Application.MainLoop.Invoke (() => Application.RequestStop ());
  476. }
  477. [Fact]
  478. [AutoInitShutdown]
  479. public async Task InvokeLeakTest ()
  480. {
  481. Random r = new ();
  482. TextField tf = new ();
  483. Application.Top.Add (tf);
  484. const int numPasses = 10;
  485. const int numIncrements = 10000;
  486. const int pollMs = 20000;
  487. var task = Task.Run (() => RunTest (r, tf, numPasses, numIncrements, pollMs));
  488. // blocks here until the RequestStop is processed at the end of the test
  489. Application.Run ();
  490. await task; // Propagate exception if any occurred
  491. Assert.Equal ((numIncrements * numPasses), tbCounter);
  492. }
  493. private static int total;
  494. private static Button btn;
  495. private static string clickMe;
  496. private static string cancel;
  497. private static string pewPew;
  498. private static int zero;
  499. private static int one;
  500. private static int two;
  501. private static int three;
  502. private static int four;
  503. private static bool taskCompleted;
  504. [Theory, AutoInitShutdown]
  505. [MemberData (nameof (TestAddIdle))]
  506. public void Mainloop_Invoke_Or_AddIdle_Can_Be_Used_For_Events_Or_Actions (Action action, string pclickMe, string pcancel, string ppewPew, int pzero, int pone, int ptwo, int pthree, int pfour)
  507. {
  508. total = 0;
  509. btn = null;
  510. clickMe = pclickMe;
  511. cancel = pcancel;
  512. pewPew = ppewPew;
  513. zero = pzero;
  514. one = pone;
  515. two = ptwo;
  516. three = pthree;
  517. four = pfour;
  518. taskCompleted = false;
  519. var btnLaunch = new Button ("Open Window");
  520. btnLaunch.Clicked += () => action ();
  521. Application.Top.Add (btnLaunch);
  522. var iterations = -1;
  523. Application.Iteration += () => {
  524. iterations++;
  525. if (iterations == 0) {
  526. Assert.Null (btn);
  527. Assert.Equal (zero, total);
  528. Assert.True (btnLaunch.ProcessKey (new KeyEvent (Key.Enter, null)));
  529. if (btn == null) {
  530. Assert.Null (btn);
  531. Assert.Equal (zero, total);
  532. } else {
  533. Assert.Equal (clickMe, btn.Text);
  534. Assert.Equal (four, total);
  535. }
  536. } else if (iterations == 1) {
  537. Assert.Equal (clickMe, btn.Text);
  538. Assert.Equal (zero, total);
  539. Assert.True (btn.ProcessKey (new KeyEvent (Key.Enter, null)));
  540. Assert.Equal (cancel, btn.Text);
  541. Assert.Equal (one, total);
  542. } else if (taskCompleted) {
  543. Application.RequestStop ();
  544. }
  545. };
  546. Application.Run ();
  547. Assert.True (taskCompleted);
  548. Assert.Equal (clickMe, btn.Text);
  549. Assert.Equal (four, total);
  550. }
  551. public static IEnumerable<object []> TestAddIdle {
  552. get {
  553. // Goes fine
  554. Action a1 = StartWindow;
  555. yield return new object [] { a1, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
  556. // Also goes fine
  557. Action a2 = () => Application.MainLoop.Invoke (StartWindow);
  558. yield return new object [] { a2, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
  559. }
  560. }
  561. private static void StartWindow ()
  562. {
  563. var startWindow = new Window {
  564. Modal = true
  565. };
  566. btn = new Button {
  567. Text = "Click Me"
  568. };
  569. btn.Clicked += RunAsyncTest;
  570. var totalbtn = new Button () {
  571. X = Pos.Right (btn),
  572. Text = "total"
  573. };
  574. totalbtn.Clicked += () => {
  575. MessageBox.Query ("Count", $"Count is {total}", "Ok");
  576. };
  577. startWindow.Add (btn);
  578. startWindow.Add (totalbtn);
  579. Application.Run (startWindow);
  580. Assert.Equal (clickMe, btn.Text);
  581. Assert.Equal (four, total);
  582. Application.RequestStop ();
  583. }
  584. private static async void RunAsyncTest ()
  585. {
  586. Assert.Equal (clickMe, btn.Text);
  587. Assert.Equal (zero, total);
  588. btn.Text = "Cancel";
  589. Interlocked.Increment (ref total);
  590. btn.SetNeedsDisplay ();
  591. await Task.Run (() => {
  592. try {
  593. Assert.Equal (cancel, btn.Text);
  594. Assert.Equal (one, total);
  595. RunSql ();
  596. } finally {
  597. SetReadyToRun ();
  598. }
  599. }).ContinueWith (async (s, e) => {
  600. await Task.Delay (1000);
  601. Assert.Equal (clickMe, btn.Text);
  602. Assert.Equal (three, total);
  603. Interlocked.Increment (ref total);
  604. Assert.Equal (clickMe, btn.Text);
  605. Assert.Equal (four, total);
  606. taskCompleted = true;
  607. }, TaskScheduler.FromCurrentSynchronizationContext ());
  608. }
  609. private static void RunSql ()
  610. {
  611. Thread.Sleep (100);
  612. Assert.Equal (cancel, btn.Text);
  613. Assert.Equal (one, total);
  614. Application.MainLoop.Invoke (() => {
  615. btn.Text = "Pew Pew";
  616. Interlocked.Increment (ref total);
  617. btn.SetNeedsDisplay ();
  618. });
  619. }
  620. private static void SetReadyToRun ()
  621. {
  622. Thread.Sleep (100);
  623. Assert.Equal (pewPew, btn.Text);
  624. Assert.Equal (two, total);
  625. Application.MainLoop.Invoke (() => {
  626. btn.Text = "Click Me";
  627. Interlocked.Increment (ref total);
  628. btn.SetNeedsDisplay ();
  629. });
  630. }
  631. }
  632. }