New test.
[mono.git] / mcs / class / corlib / System.Runtime.InteropServices / CriticalHandle.cs
1 //
2 // System.Runtime.InteropServices.CriticalHandle
3 //
4 // Author:
5 //   Kazuki Oikawa  (kazuki@panicode.com)
6 //
7
8 #if NET_2_0
9
10 using System;
11 using System.Runtime.ConstrainedExecution;
12 using System.Runtime.Serialization;
13
14 namespace System.Runtime.InteropServices
15 {
16         public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
17         {
18                 protected IntPtr handle;
19                 bool _disposed = false;
20
21                 protected CriticalHandle (IntPtr invalidHandleValue)
22                 {
23                         handle = invalidHandleValue;
24                 }
25
26                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
27                 ~CriticalHandle ()
28                 {
29                         Dispose ();
30                 }
31
32                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
33                 public void Close ()
34                 {
35                         Dispose ();
36                 }
37
38                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
39                 public void Dispose ()
40                 {
41                         if (_disposed)
42                                 return;
43
44                         _disposed = true;
45                         if (IsInvalid)
46                                 return;
47
48                         if (ReleaseHandle ()) {
49                                 GC.SuppressFinalize (this);
50                         } else {
51                                 // Failed in release...
52                         }
53                 }
54
55                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
56                 protected abstract bool ReleaseHandle ();
57
58                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
59                 protected void SetHandle (IntPtr handle)
60                 {
61                         this.handle = handle;
62                 }
63
64                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
65                 public void SetHandleAsInvalid()
66                 {
67                         _disposed = true;
68                 }
69
70                 public bool IsClosed {
71                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
72                         get { return _disposed; }
73                 }
74
75                 public abstract bool IsInvalid {
76                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
77                         get;
78                 }
79         }
80 }
81 #endif