Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100755 70 lines (62 sloc) 2.145 kb
1203dc0 @mikehadlow initial commit
authored
1 using System;
2 using System.Diagnostics;
3 using System.Threading;
4
5 namespace Mike.MQShootout
6 {
7 public class MessageReceivingMachine
8 {
9 private readonly IMessageReceiver<byte[]> messageReceiver;
10 private readonly long numberOfMessages;
11
12 public MessageReceivingMachine(IMessageReceiver<byte[]> messageReceiver, long numberOfMessages)
13 {
14 this.messageReceiver = messageReceiver;
15 this.messageReceiver.ReceiveMessage(ReceiveMessage);
16 this.numberOfMessages = numberOfMessages;
17 }
18
19 private bool started = false;
20 private bool completed = false;
21 private long messageCounter = 0;
22 private readonly Stopwatch stopwatch = new Stopwatch();
23 private readonly object theLock = new object();
24
25 private void ReceiveMessage(byte[] message)
26 {
27 if (!started)
28 {
29 lock (theLock)
30 {
31 if (!started)
32 {
33 started = true;
34 stopwatch.Start();
35 }
36 }
37 }
38
39 Interlocked.Increment(ref messageCounter);
40
41 if (messageCounter == numberOfMessages)
42 {
43 lock (theLock)
44 {
45 stopwatch.Stop();
46 var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
47 Console.WriteLine("{0} messages received in {1} ms", numberOfMessages, elapsedMilliseconds);
48 Console.WriteLine("Received {0} per second", elapsedMilliseconds == 0 ? 0L : (1000 * numberOfMessages) / elapsedMilliseconds);
49 completed = true;
50 }
51 }
52 }
53
54 public void WaitForCompletion()
55 {
56 while (NotCompleted())
57 {
58 Thread.Sleep(100);
59 }
60 }
61
62 private bool NotCompleted()
63 {
64 lock (theLock)
65 {
66 return !completed;
67 }
68 }
69 }
70 }
Something went wrong with that request. Please try again.