SynchronizatonContextTests.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // Alias Console to MockConsole so we don't accidentally use Console
  2. using UnitTests;
  3. namespace UnitTests.ApplicationTests;
  4. public class SyncrhonizationContextTests
  5. {
  6. [Fact]
  7. public void SynchronizationContext_CreateCopy ()
  8. {
  9. Application.Init ("fake");
  10. SynchronizationContext context = SynchronizationContext.Current;
  11. Assert.NotNull (context);
  12. SynchronizationContext contextCopy = context.CreateCopy ();
  13. Assert.NotNull (contextCopy);
  14. Assert.NotEqual (context, contextCopy);
  15. Application.Shutdown ();
  16. }
  17. private readonly object _lockPost = new ();
  18. [Theory]
  19. [InlineData ("fake")]
  20. [InlineData ("windows")]
  21. [InlineData ("dotnet")]
  22. // [InlineData ("unix")]
  23. public void SynchronizationContext_Post (string driverName = null)
  24. {
  25. lock (_lockPost)
  26. {
  27. Application.Init (driverName);
  28. SynchronizationContext context = SynchronizationContext.Current;
  29. var success = false;
  30. Task.Run (() =>
  31. {
  32. while (Application.Current is null || Application.Current is { IsRunning: false })
  33. {
  34. Thread.Sleep (500);
  35. }
  36. // non blocking
  37. context.Post (
  38. delegate
  39. {
  40. success = true;
  41. // then tell the application to quit
  42. Application.Invoke (() => Application.RequestStop ());
  43. },
  44. null
  45. );
  46. if (Application.Current is { IsRunning: true })
  47. {
  48. Assert.False (success);
  49. }
  50. }
  51. );
  52. // blocks here until the RequestStop is processed at the end of the test
  53. Application.Run ().Dispose ();
  54. Assert.True (success);
  55. Application.Shutdown ();
  56. }
  57. }
  58. [Fact]
  59. [AutoInitShutdown]
  60. public void SynchronizationContext_Send ()
  61. {
  62. SynchronizationContext context = SynchronizationContext.Current;
  63. var success = false;
  64. Task.Run (
  65. () =>
  66. {
  67. Thread.Sleep (500);
  68. // blocking
  69. context.Send (
  70. delegate
  71. {
  72. success = true;
  73. // then tell the application to quit
  74. Application.Invoke (() => Application.RequestStop ());
  75. },
  76. null
  77. );
  78. Assert.True (success);
  79. }
  80. );
  81. // blocks here until the RequestStop is processed at the end of the test
  82. Application.Run ().Dispose ();
  83. Assert.True (success);
  84. Application.Shutdown ();
  85. }
  86. }