/source/test/NOS.Registration.Tests/CrossContextSynchronizationSpecs.cs

http://github.com/agross/netopenspace · C# · 70 lines · 55 code · 15 blank · 0 comment · 0 complexity · c9c2c7ec6be49ad0ddb529b2f0768085 MD5 · raw file

  1. using System;
  2. using System.Threading;
  3. using Machine.Specifications;
  4. namespace NOS.Registration.Tests
  5. {
  6. [Subject(typeof(CrossContextSynchronizer))]
  7. public class When_a_reader_tries_to_read_while_a_writer_is_active
  8. {
  9. static ISynchronizer Synchronizer;
  10. static int SharedValue;
  11. static int ReadValue;
  12. Establish context = () => { Synchronizer = new CrossContextSynchronizer(); };
  13. Because of = () =>
  14. {
  15. SharedValue = 25;
  16. AutoResetEvent writerReady = new AutoResetEvent(false);
  17. Thread reader = new Thread(() => Synchronizer.Lock(() =>
  18. {
  19. Console.WriteLine("Reading");
  20. ReadValue = SharedValue;
  21. }))
  22. { Name = "Reader" };
  23. Thread writer = new Thread(() => Synchronizer.Lock(() =>
  24. {
  25. writerReady.Set();
  26. Thread.Sleep(1000);
  27. Console.WriteLine("Writing");
  28. SharedValue = 42;
  29. }))
  30. { Name = "Writer" };
  31. writer.Start();
  32. writerReady.WaitOne();
  33. reader.Start();
  34. writer.Join();
  35. reader.Join();
  36. };
  37. It should_write_the_new_value = () => SharedValue.ShouldEqual(42);
  38. It should_read_after_the_writer_finished = () => ReadValue.ShouldEqual(42);
  39. }
  40. [Subject(typeof(CrossContextSynchronizer))]
  41. public class When_locks_are_nested_in_the_same_thread
  42. {
  43. static ISynchronizer Synchronizer;
  44. static bool Status;
  45. Establish context = () => { Synchronizer = new CrossContextSynchronizer(); };
  46. Because of = () =>
  47. {
  48. Thread worker = new Thread(() => Synchronizer.Lock(() => Synchronizer.Lock(() => { Status = true; })))
  49. { Name = "Worker" };
  50. worker.Start();
  51. worker.Join(TimeSpan.FromMinutes(1));
  52. };
  53. It should_succeed = () => Status.ShouldBeTrue();
  54. }
  55. }