SingleAssignment.cs 2.2 KB

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