MainLoopTests.cs 19 KB

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