MainLoopTests.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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. [Fact]
  217. public void AddTimer_Run_Called ()
  218. {
  219. var ml = new MainLoop (new FakeMainLoop ());
  220. var ms = 100;
  221. var callbackCount = 0;
  222. Func<MainLoop, bool> callback = (loop) => {
  223. callbackCount++;
  224. ml.Stop ();
  225. return true;
  226. };
  227. var token = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback);
  228. ml.Run ();
  229. Assert.True (ml.RemoveTimeout (token));
  230. Assert.Equal (1, callbackCount);
  231. }
  232. [Fact]
  233. public async Task AddTimer_Duplicate_Keys_Not_Allowed ()
  234. {
  235. var ml = new MainLoop (new FakeMainLoop ());
  236. const int ms = 100;
  237. object token1 = null, token2 = null;
  238. var callbackCount = 0;
  239. Func<MainLoop, bool> callback = (loop) => {
  240. callbackCount++;
  241. if (callbackCount == 2) ml.Stop ();
  242. return true;
  243. };
  244. var task1 = new Task (() => token1 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback));
  245. var task2 = new Task (() => token2 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback));
  246. Assert.Null (token1);
  247. Assert.Null (token2);
  248. task1.Start ();
  249. task2.Start ();
  250. ml.Run ();
  251. Assert.NotNull (token1);
  252. Assert.NotNull (token2);
  253. await Task.WhenAll (task1, task2);
  254. Assert.True (ml.RemoveTimeout (token1));
  255. Assert.True (ml.RemoveTimeout (token2));
  256. Assert.Equal (2, callbackCount);
  257. }
  258. [Fact]
  259. public void AddTimer_In_Parallel_Wont_Throw ()
  260. {
  261. var ml = new MainLoop (new FakeMainLoop ());
  262. const int ms = 100;
  263. object token1 = null, token2 = null;
  264. var callbackCount = 0;
  265. Func<MainLoop, bool> callback = (loop) => {
  266. callbackCount++;
  267. if (callbackCount == 2) ml.Stop ();
  268. return true;
  269. };
  270. Parallel.Invoke (
  271. () => token1 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback),
  272. () => token2 = ml.AddTimeout (TimeSpan.FromMilliseconds (ms), callback)
  273. );
  274. ml.Run ();
  275. Assert.NotNull (token1);
  276. Assert.NotNull (token2);
  277. Assert.True (ml.RemoveTimeout (token1));
  278. Assert.True (ml.RemoveTimeout (token2));
  279. Assert.Equal (2, callbackCount);
  280. }
  281. class MillisecondTolerance : IEqualityComparer<TimeSpan> {
  282. int _tolerance = 0;
  283. public MillisecondTolerance (int tolerance) { _tolerance = tolerance; }
  284. public bool Equals (TimeSpan x, TimeSpan y) => Math.Abs (x.Milliseconds - y.Milliseconds) <= _tolerance;
  285. public int GetHashCode (TimeSpan obj) => obj.GetHashCode ();
  286. }
  287. [Fact]
  288. public void AddTimer_Run_CalledAtApproximatelyRightTime ()
  289. {
  290. var ml = new MainLoop (new FakeMainLoop ());
  291. var ms = TimeSpan.FromMilliseconds (50);
  292. var watch = new System.Diagnostics.Stopwatch ();
  293. var callbackCount = 0;
  294. Func<MainLoop, bool> callback = (loop) => {
  295. watch.Stop ();
  296. callbackCount++;
  297. ml.Stop ();
  298. return true;
  299. };
  300. var token = ml.AddTimeout (ms, callback);
  301. watch.Start ();
  302. ml.Run ();
  303. // +/- 100ms should be good enuf
  304. // https://github.com/xunit/assert.xunit/pull/25
  305. Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
  306. Assert.True (ml.RemoveTimeout (token));
  307. Assert.Equal (1, callbackCount);
  308. }
  309. [Fact]
  310. public void AddTimer_Run_CalledTwiceApproximatelyRightTime ()
  311. {
  312. var ml = new MainLoop (new FakeMainLoop ());
  313. var ms = TimeSpan.FromMilliseconds (50);
  314. var watch = new System.Diagnostics.Stopwatch ();
  315. var callbackCount = 0;
  316. Func<MainLoop, bool> callback = (loop) => {
  317. callbackCount++;
  318. if (callbackCount == 2) {
  319. watch.Stop ();
  320. ml.Stop ();
  321. }
  322. return true;
  323. };
  324. var token = ml.AddTimeout (ms, callback);
  325. watch.Start ();
  326. ml.Run ();
  327. // +/- 100ms should be good enuf
  328. // https://github.com/xunit/assert.xunit/pull/25
  329. Assert.Equal (ms * callbackCount, watch.Elapsed, new MillisecondTolerance (100));
  330. Assert.True (ml.RemoveTimeout (token));
  331. Assert.Equal (2, callbackCount);
  332. }
  333. [Fact]
  334. public void AddTimer_Remove_NotCalled ()
  335. {
  336. var ml = new MainLoop (new FakeMainLoop ());
  337. var ms = TimeSpan.FromMilliseconds (50);
  338. // Force stop if 10 iterations
  339. var stopCount = 0;
  340. Func<bool> fnStop = () => {
  341. stopCount++;
  342. if (stopCount == 10) ml.Stop ();
  343. return true;
  344. };
  345. ml.AddIdle (fnStop);
  346. var callbackCount = 0;
  347. Func<MainLoop, bool> callback = (loop) => {
  348. callbackCount++;
  349. return true;
  350. };
  351. var token = ml.AddTimeout (ms, callback);
  352. Assert.True (ml.RemoveTimeout (token));
  353. ml.Run ();
  354. Assert.Equal (0, callbackCount);
  355. }
  356. [Fact]
  357. public void AddTimer_ReturnFalse_StopsBeingCalled ()
  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. Thread.Sleep (10); // Sleep to enable timer to fire
  365. stopCount++;
  366. if (stopCount == 10) ml.Stop ();
  367. return true;
  368. };
  369. ml.AddIdle (fnStop);
  370. var callbackCount = 0;
  371. Func<MainLoop, bool> callback = (loop) => {
  372. callbackCount++;
  373. return false;
  374. };
  375. var token = ml.AddTimeout (ms, callback);
  376. ml.Run ();
  377. Assert.Equal (1, callbackCount);
  378. Assert.Equal (10, stopCount);
  379. Assert.False (ml.RemoveTimeout (token));
  380. }
  381. // Invoke Tests
  382. // TODO: Test with threading scenarios
  383. [Fact]
  384. public void Invoke_Adds_Idle ()
  385. {
  386. var ml = new MainLoop (new FakeMainLoop ());
  387. var actionCalled = 0;
  388. ml.Invoke (() => { actionCalled++; });
  389. ml.MainIteration ();
  390. Assert.Equal (1, actionCalled);
  391. }
  392. [Fact]
  393. public void Internal_Tests ()
  394. {
  395. var testMainloop = new TestMainloop ();
  396. var mainloop = new MainLoop (testMainloop);
  397. Assert.Empty (mainloop.timeouts);
  398. Assert.Empty (mainloop.idleHandlers);
  399. Assert.NotNull (new MainLoop.Timeout () {
  400. Span = new TimeSpan (),
  401. Callback = (_) => true
  402. });
  403. }
  404. private class TestMainloop : IMainLoopDriver {
  405. private MainLoop mainLoop;
  406. public bool EventsPending (bool wait)
  407. {
  408. throw new NotImplementedException ();
  409. }
  410. public void MainIteration ()
  411. {
  412. throw new NotImplementedException ();
  413. }
  414. public void Setup (MainLoop mainLoop)
  415. {
  416. this.mainLoop = mainLoop;
  417. }
  418. public void Wakeup ()
  419. {
  420. throw new NotImplementedException ();
  421. }
  422. }
  423. // TODO: EventsPending tests
  424. // - wait = true
  425. // - wait = false
  426. // TODO: Add IMainLoop tests
  427. volatile static int tbCounter = 0;
  428. static ManualResetEventSlim _wakeUp = new ManualResetEventSlim (false);
  429. private static void Launch (Random r, TextField tf, int target)
  430. {
  431. Task.Run (() => {
  432. Thread.Sleep (r.Next (2, 4));
  433. Application.MainLoop.Invoke (() => {
  434. tf.Text = $"index{r.Next ()}";
  435. Interlocked.Increment (ref tbCounter);
  436. if (target == tbCounter) // On last increment wake up the check
  437. _wakeUp.Set ();
  438. });
  439. });
  440. }
  441. private static void RunTest (Random r, TextField tf, int numPasses, int numIncrements, int pollMs)
  442. {
  443. for (int j = 0; j < numPasses; j++) {
  444. _wakeUp.Reset ();
  445. for (var i = 0; i < numIncrements; i++) Launch (r, tf, (j + 1) * numIncrements);
  446. while (tbCounter != (j + 1) * numIncrements) // Wait for tbCounter to reach expected value
  447. {
  448. var tbNow = tbCounter;
  449. _wakeUp.Wait (pollMs);
  450. if (tbCounter == tbNow) {
  451. // No change after wait: Idle handlers added via Application.MainLoop.Invoke have gone missing
  452. Application.MainLoop.Invoke (() => Application.RequestStop ());
  453. throw new TimeoutException (
  454. $"Timeout: Increment lost. tbCounter ({tbCounter}) didn't " +
  455. $"change after waiting {pollMs} ms. Failed to reach {(j + 1) * numIncrements} on pass {j + 1}");
  456. }
  457. };
  458. }
  459. Application.MainLoop.Invoke (() => Application.RequestStop ());
  460. }
  461. [Fact]
  462. [AutoInitShutdown]
  463. public async Task InvokeLeakTest ()
  464. {
  465. Random r = new ();
  466. TextField tf = new ();
  467. Application.Top.Add (tf);
  468. const int numPasses = 5;
  469. const int numIncrements = 5000;
  470. const int pollMs = 10000;
  471. var task = Task.Run (() => RunTest (r, tf, numPasses, numIncrements, pollMs));
  472. // blocks here until the RequestStop is processed at the end of the test
  473. Application.Run ();
  474. await task; // Propagate exception if any occurred
  475. Assert.Equal (numIncrements * numPasses, tbCounter);
  476. }
  477. private static int total;
  478. private static Button btn;
  479. private static string clickMe;
  480. private static string cancel;
  481. private static string pewPew;
  482. private static int zero;
  483. private static int one;
  484. private static int two;
  485. private static int three;
  486. private static int four;
  487. private static bool taskCompleted;
  488. [Theory, AutoInitShutdown]
  489. [MemberData (nameof (TestAddIdle))]
  490. 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)
  491. {
  492. total = 0;
  493. btn = null;
  494. clickMe = pclickMe;
  495. cancel = pcancel;
  496. pewPew = ppewPew;
  497. zero = pzero;
  498. one = pone;
  499. two = ptwo;
  500. three = pthree;
  501. four = pfour;
  502. taskCompleted = false;
  503. var btnLaunch = new Button ("Open Window");
  504. btnLaunch.Clicked += () => action ();
  505. Application.Top.Add (btnLaunch);
  506. var iterations = -1;
  507. Application.Iteration += () => {
  508. iterations++;
  509. if (iterations == 0) {
  510. Assert.Null (btn);
  511. Assert.Equal (zero, total);
  512. Assert.True (btnLaunch.ProcessKey (new KeyEvent (Key.Enter, null)));
  513. if (btn == null) {
  514. Assert.Null (btn);
  515. Assert.Equal (zero, total);
  516. } else {
  517. Assert.Equal (clickMe, btn.Text);
  518. Assert.Equal (four, total);
  519. }
  520. } else if (iterations == 1) {
  521. Assert.Equal (clickMe, btn.Text);
  522. Assert.Equal (zero, total);
  523. Assert.True (btn.ProcessKey (new KeyEvent (Key.Enter, null)));
  524. Assert.Equal (cancel, btn.Text);
  525. Assert.Equal (one, total);
  526. } else if (taskCompleted) Application.RequestStop ();
  527. };
  528. Application.Run ();
  529. Assert.True (taskCompleted);
  530. Assert.Equal (clickMe, btn.Text);
  531. Assert.Equal (four, total);
  532. }
  533. public static IEnumerable<object []> TestAddIdle {
  534. get {
  535. // Goes fine
  536. Action a1 = StartWindow;
  537. yield return new object [] { a1, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
  538. // Also goes fine
  539. Action a2 = () => Application.MainLoop.Invoke (StartWindow);
  540. yield return new object [] { a2, "Click Me", "Cancel", "Pew Pew", 0, 1, 2, 3, 4 };
  541. }
  542. }
  543. private static void StartWindow ()
  544. {
  545. var startWindow = new Window {
  546. Modal = true
  547. };
  548. btn = new Button {
  549. Text = "Click Me"
  550. };
  551. btn.Clicked += RunAsyncTest;
  552. var totalbtn = new Button () {
  553. X = Pos.Right (btn),
  554. Text = "total"
  555. };
  556. totalbtn.Clicked += () => {
  557. MessageBox.Query ("Count", $"Count is {total}", "Ok");
  558. };
  559. startWindow.Add (btn);
  560. startWindow.Add (totalbtn);
  561. Application.Run (startWindow);
  562. Assert.Equal (clickMe, btn.Text);
  563. Assert.Equal (four, total);
  564. Application.RequestStop ();
  565. }
  566. private static async void RunAsyncTest ()
  567. {
  568. Assert.Equal (clickMe, btn.Text);
  569. Assert.Equal (zero, total);
  570. btn.Text = "Cancel";
  571. Interlocked.Increment (ref total);
  572. btn.SetNeedsDisplay ();
  573. await Task.Run (() => {
  574. try {
  575. Assert.Equal (cancel, btn.Text);
  576. Assert.Equal (one, total);
  577. RunSql ();
  578. } finally {
  579. SetReadyToRun ();
  580. }
  581. }).ContinueWith (async (s, e) => {
  582. await Task.Delay (1000);
  583. Assert.Equal (clickMe, btn.Text);
  584. Assert.Equal (three, total);
  585. Interlocked.Increment (ref total);
  586. Assert.Equal (clickMe, btn.Text);
  587. Assert.Equal (four, total);
  588. taskCompleted = true;
  589. }, TaskScheduler.FromCurrentSynchronizationContext ());
  590. }
  591. private static void RunSql ()
  592. {
  593. Thread.Sleep (100);
  594. Assert.Equal (cancel, btn.Text);
  595. Assert.Equal (one, total);
  596. Application.MainLoop.Invoke (() => {
  597. btn.Text = "Pew Pew";
  598. Interlocked.Increment (ref total);
  599. btn.SetNeedsDisplay ();
  600. });
  601. }
  602. private static void SetReadyToRun ()
  603. {
  604. Thread.Sleep (100);
  605. Assert.Equal (pewPew, btn.Text);
  606. Assert.Equal (two, total);
  607. Application.MainLoop.Invoke (() => {
  608. btn.Text = "Click Me";
  609. Interlocked.Increment (ref total);
  610. btn.SetNeedsDisplay ();
  611. });
  612. }
  613. }
  614. }