New tests.
[mono.git] / mcs / class / System.Web.Mvc2 / System.Web.Mvc / Async / OperationCounter.cs
1 /* ****************************************************************************\r
2  *\r
3  * Copyright (c) Microsoft Corporation. All rights reserved.\r
4  *\r
5  * This software is subject to the Microsoft Public License (Ms-PL). \r
6  * A copy of the license can be found in the license.htm file included \r
7  * in this distribution.\r
8  *\r
9  * You must not remove this notice, or any other, from this software.\r
10  *\r
11  * ***************************************************************************/\r
12 \r
13 namespace System.Web.Mvc.Async {\r
14     using System;\r
15     using System.Threading;\r
16 \r
17     public sealed class OperationCounter {\r
18 \r
19         private int _count;\r
20 \r
21         public int Count {\r
22             get {\r
23                 return Thread.VolatileRead(ref _count);\r
24             }\r
25         }\r
26 \r
27         public event EventHandler Completed;\r
28 \r
29         private int AddAndExecuteCallbackIfCompleted(int value) {\r
30             int newCount = Interlocked.Add(ref _count, value);\r
31             if (newCount == 0) {\r
32                 OnCompleted();\r
33             }\r
34 \r
35             return newCount;\r
36         }\r
37 \r
38         public int Decrement() {\r
39             return AddAndExecuteCallbackIfCompleted(-1);\r
40         }\r
41 \r
42         public int Decrement(int value) {\r
43             return AddAndExecuteCallbackIfCompleted(-value);\r
44         }\r
45 \r
46         public int Increment() {\r
47             return AddAndExecuteCallbackIfCompleted(1);\r
48         }\r
49 \r
50         public int Increment(int value) {\r
51             return AddAndExecuteCallbackIfCompleted(value);\r
52         }\r
53 \r
54         private void OnCompleted() {\r
55             EventHandler handler = Completed;\r
56             if (handler != null) {\r
57                 handler(this, EventArgs.Empty);\r
58             }\r
59         }\r
60 \r
61     }\r
62 }\r