[System.Private.CoreLib] Remove unused members and further cleanups
[mono-project.git] / mcs / class / System.Private.CoreLib / System.Threading / RegisteredWaitHandle.cs
blob899a6a171a5035713907ddbf01905d9d20c28ec6
1 using System.Runtime.InteropServices;
3 namespace System.Threading
5 public sealed class RegisteredWaitHandle : MarshalByRefObject
7 WaitHandle _waitObject;
8 WaitOrTimerCallback _callback;
9 object _state;
10 WaitHandle _finalEvent;
11 ManualResetEvent _cancelEvent;
12 TimeSpan _timeout;
13 int _callsInProcess;
14 bool _executeOnlyOnce;
15 bool _unregistered;
17 internal RegisteredWaitHandle (WaitHandle waitObject, WaitOrTimerCallback callback, object state, TimeSpan timeout, bool executeOnlyOnce)
19 _waitObject = waitObject;
20 _callback = callback;
21 _state = state;
22 _timeout = timeout;
23 _executeOnlyOnce = executeOnlyOnce;
24 _cancelEvent = new ManualResetEvent (false);
27 internal void Wait (object? state)
29 bool release = false;
30 try {
31 _waitObject.SafeWaitHandle.DangerousAddRef (ref release);
32 try {
33 WaitHandle[] waits = new WaitHandle[] {_waitObject, _cancelEvent};
34 do {
35 int signal = WaitHandle.WaitAny (waits, _timeout, false);
36 if (!_unregistered) {
37 lock (this) {
38 _callsInProcess++;
40 ThreadPool.QueueUserWorkItem (new WaitCallback (DoCallBack), (signal == WaitHandle.WaitTimeout));
42 } while (!_unregistered && !_executeOnlyOnce);
43 } catch {
46 lock (this) {
47 _unregistered = true;
48 if (_callsInProcess == 0 && _finalEvent != null)
49 throw new NotImplementedException ();
51 } catch (ObjectDisposedException) {
52 // Can happen if we called Unregister before we had time to execute Wait
53 if (release)
54 throw;
55 } finally {
56 if (release)
57 _waitObject.SafeWaitHandle.DangerousRelease ();
61 void DoCallBack (object? timedOut)
63 try {
64 if (_callback != null)
65 _callback (_state, (bool)timedOut!);
66 } finally {
67 lock (this) {
68 _callsInProcess--;
69 if (_unregistered && _callsInProcess == 0 && _finalEvent != null)
70 EventWaitHandle.Set (_finalEvent.SafeWaitHandle);
75 public bool Unregister(WaitHandle waitObject)
77 lock (this) {
78 if (_unregistered)
79 return false;
81 _finalEvent = waitObject;
82 _unregistered = true;
83 _cancelEvent.Set();
85 return true;