PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 5ms RepoModel.GetById 26ms app.codeStats 10ms

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