MainLoopTests.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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.MainLoopDriver);
  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.RunIteration ();
  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.RunIteration ();
  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.RunIteration ();
  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.RunIteration ();
  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.RunIteration ();
  126. Assert.Equal (1, functionCalled);
  127. functionCalled = 0;
  128. Assert.True (ml.RemoveIdle (fn));
  129. Assert.Empty (ml.IdleHandlers);
  130. ml.RunIteration ();
  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.RunIteration ();
  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 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 Iteration ()
  434. {
  435. throw new NotImplementedException ();
  436. }
  437. public void TearDown ()
  438. {
  439. throw new NotImplementedException ();
  440. }
  441. public void Setup (MainLoop mainLoop)
  442. {
  443. this.mainLoop = mainLoop;
  444. }
  445. public void Wakeup ()
  446. {
  447. throw new NotImplementedException ();
  448. }
  449. }
  450. // TODO: EventsPending tests
  451. // - wait = true
  452. // - wait = false
  453. // TODO: Add IMainLoop tests
  454. volatile static int tbCounter = 0;
  455. static ManualResetEventSlim _wakeUp = new ManualResetEventSlim (false);
  456. private static void Launch (Random r, TextField tf, int target)
  457. {
  458. Task.Run (() => {
  459. Thread.Sleep (r.Next (2, 4));
  460. Application.MainLoop.Invoke (() => {
  461. tf.Text = $"index{r.Next ()}";
  462. Interlocked.Increment (ref tbCounter);
  463. if (target == tbCounter) // On last increment wake up the check
  464. _wakeUp.Set ();
  465. });
  466. });
  467. }
  468. private static void RunTest (Random r, TextField tf, int numPasses, int numIncrements, int pollMs)
  469. {
  470. for (int j = 0; j < numPasses; j++) {
  471. _wakeUp.Reset ();
  472. for (var i = 0; i < numIncrements; i++) Launch (r, tf, (j + 1) * numIncrements);
  473. while (tbCounter != (j + 1) * numIncrements) // Wait for tbCounter to reach expected value
  474. {
  475. var tbNow = tbCounter;
  476. _wakeUp.Wait (pollMs);
  477. if (tbCounter == tbNow) {
  478. // No change after wait: Idle handlers added via Application.MainLoop.Invoke have gone missing
  479. Application.MainLoop.Invoke (() => Application.RequestStop ());
  480. throw new TimeoutException (
  481. $"Timeout: Increment lost. tbCounter ({tbCounter}) didn't " +
  482. $"change after waiting {pollMs} ms. Failed to reach {(j + 1) * numIncrements} on pass {j + 1}");
  483. }
  484. };
  485. }
  486. Application.MainLoop.Invoke (() => Application.RequestStop ());
  487. }
  488. [Fact]
  489. [AutoInitShutdown]
  490. public async Task InvokeLeakTest ()
  491. {
  492. Random r = new ();
  493. TextField tf = new ();
  494. Application.Top.Add (tf);
  495. const int numPasses = 5;
  496. const int numIncrements = 5000;
  497. const int pollMs = 10000;
  498. var task = Task.Run (() => RunTest (r, tf, numPasses, numIncrements, pollMs));
  499. // blocks here until the RequestStop is processed at the end of the test
  500. Application.Run ();
  501. await task; // Propagate exception if any occurred
  502. Assert.Equal (numIncrements * numPasses, tbCounter);
  503. }
  504. private static int total;
  505. private static Button btn;
  506. private static string clickMe;
  507. private static string cancel;
  508. private static string pewPew;
  509. private static int zero;
  510. private static int one;
  511. private static int two;
  512. private static int three;
  513. private static int four;
  514. private static bool taskCompleted;
  515. [Theory, AutoInitShutdown]
  516. [MemberData (nameof (TestAddIdle))]
  517. 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)
  518. {
  519. total = 0;
  520. btn = null;
  521. clickMe = pclickMe;
  522. cancel = pcancel;
  523. pewPew = ppewPew;
  524. zero = pzero;
  525. one = pone;
  526. two = ptwo;
  527. three = pthree;
  528. four = pfour;
  529. taskCompleted = false;
  530. var btnLaunch = new Button ("Open Window");
  531. btnLaunch.Clicked += (s,e) => action ();
  532. Application.Top.Add (btnLaunch);
  533. var iterations = -1;
  534. Application.Iteration += () => {
  535. iterations++;
  536. if (iterations == 0) {
  537. Assert.Null (btn);
  538. Assert.Equal (zero, total);
  539. Assert.True (btnLaunch.ProcessKey (new KeyEvent (Key.Enter, null)));
  540. if (btn == null) {
  541. Assert.Null (btn);
  542. Assert.Equal (zero, total);
  543. } else {
  544. Assert.Equal (clickMe, btn.Text);
  545. Assert.Equal (four, total);
  546. }
  547. } else if (iterations == 1) {
  548. Assert.Equal (clickMe, btn.Text);
  549. Assert.Equal (zero, total);
  550. Assert.True (btn.ProcessKey (new KeyEvent (Key.Enter, null)));
  551. Assert.Equal (cancel, btn.Text);
  552. Assert.Equal (one, total);
  553. } else if (taskCompleted) {
  554. Application.RequestStop ();
  555. }
  556. };
  557. Application.Run ();
  558. Assert.True (taskCompleted);
  559. Assert.Equal (clickMe, btn.Text);
  560. Assert.Equal (four, total);
  561. }
  562. public static IEnumerable<object []> TestAddIdle {
  563. get {
  564. // Goes fine
  565. Action a1 = StartWindow;
  566. yield return new object [] { a1, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
  567. // Also goes fine
  568. Action a2 = () => Application.MainLoop.Invoke (StartWindow);
  569. yield return new object [] { a2, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
  570. }
  571. }
  572. private static void StartWindow ()
  573. {
  574. var startWindow = new Window {
  575. Modal = true
  576. };
  577. btn = new Button {
  578. Text = "Click Me"
  579. };
  580. btn.Clicked += RunAsyncTest;
  581. var totalbtn = new Button () {
  582. X = Pos.Right (btn),
  583. Text = "total"
  584. };
  585. totalbtn.Clicked += (s,e) => {
  586. MessageBox.Query ("Count", $"Count is {total}", "Ok");
  587. };
  588. startWindow.Add (btn);
  589. startWindow.Add (totalbtn);
  590. Application.Run (startWindow);
  591. Assert.Equal (clickMe, btn.Text);
  592. Assert.Equal (four, total);
  593. Application.RequestStop ();
  594. }
  595. private static async void RunAsyncTest (object sender, EventArgs e)
  596. {
  597. Assert.Equal (clickMe, btn.Text);
  598. Assert.Equal (zero, total);
  599. btn.Text = "Cancel";
  600. Interlocked.Increment (ref total);
  601. btn.SetNeedsDisplay ();
  602. await Task.Run (() => {
  603. try {
  604. Assert.Equal (cancel, btn.Text);
  605. Assert.Equal (one, total);
  606. RunSql ();
  607. } finally {
  608. SetReadyToRun ();
  609. }
  610. }).ContinueWith (async (s, e) => {
  611. await Task.Delay (1000);
  612. Assert.Equal (clickMe, btn.Text);
  613. Assert.Equal (three, total);
  614. Interlocked.Increment (ref total);
  615. Assert.Equal (clickMe, btn.Text);
  616. Assert.Equal (four, total);
  617. taskCompleted = true;
  618. }, TaskScheduler.FromCurrentSynchronizationContext ());
  619. }
  620. private static void RunSql ()
  621. {
  622. Thread.Sleep (100);
  623. Assert.Equal (cancel, btn.Text);
  624. Assert.Equal (one, total);
  625. Application.MainLoop.Invoke (() => {
  626. btn.Text = "Pew Pew";
  627. Interlocked.Increment (ref total);
  628. btn.SetNeedsDisplay ();
  629. });
  630. }
  631. private static void SetReadyToRun ()
  632. {
  633. Thread.Sleep (100);
  634. Assert.Equal (pewPew, btn.Text);
  635. Assert.Equal (two, total);
  636. Application.MainLoop.Invoke (() => {
  637. btn.Text = "Click Me";
  638. Interlocked.Increment (ref total);
  639. btn.SetNeedsDisplay ();
  640. });
  641. }
  642. }
  643. }