SingleAssignment.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. #if STRESS
  5. using System;
  6. using System.Reactive.Disposables;
  7. using System.Reflection;
  8. using System.Threading;
  9. namespace ReactiveTests.Stress.Disposables
  10. {
  11. public class SingleAssignment
  12. {
  13. /// <summary>
  14. /// Allocates a SingleAssignmentDisposable and assigns a disposable object at a random time. Also disposes the container at a random time.
  15. /// Expected behavior is to see the assigned disposable getting disposed no matter what.
  16. /// </summary>
  17. public static void RandomAssignAndDispose()
  18. {
  19. Console.Title = MethodInfo.GetCurrentMethod().Name + " - 0% complete";
  20. for (int i = 1; i <= 100; i++)
  21. {
  22. for (int j = 0; j < 10; j++)
  23. {
  24. Impl();
  25. }
  26. Console.Title = MethodInfo.GetCurrentMethod().Name + " - " + i + "% complete";
  27. }
  28. }
  29. private static void Impl()
  30. {
  31. var rand = new Random();
  32. for (int i = 0; i < 1000; i++)
  33. {
  34. var d = new SingleAssignmentDisposable();
  35. var e = new ManualResetEvent(false);
  36. var cd = new CountdownEvent(2);
  37. var sleep1 = rand.Next(0, 1) == 0 ? 0 : rand.Next(2, 100);
  38. var sleep2 = rand.Next(0, 1) == 0 ? 0 : rand.Next(2, 100);
  39. ThreadPool.QueueUserWorkItem(_ =>
  40. {
  41. Helpers.SleepOrSpin(sleep1);
  42. Console.Write("{DB} ");
  43. d.Dispose();
  44. Console.Write("{DE} ");
  45. cd.Signal();
  46. });
  47. ThreadPool.QueueUserWorkItem(_ =>
  48. {
  49. Helpers.SleepOrSpin(sleep2);
  50. Console.Write("{AB} ");
  51. d.Disposable = Disposable.Create(() => e.Set());
  52. Console.Write("{AE} ");
  53. cd.Signal();
  54. });
  55. e.WaitOne();
  56. cd.Wait();
  57. Console.WriteLine(".");
  58. }
  59. }
  60. }
  61. }
  62. #endif