Welcome to mirror list, hosted at ThFree Co, Russian Federation.

LowLevelMonitor.Windows.cs « Threading « System « src « System.Private.CoreLib « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a492e3acbd730547456256ee3d2a8ef5095ce8f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Diagnostics;
using System.Runtime.InteropServices;
using Internal.Runtime.Augments;

namespace System.Threading
{
    /// <summary>
    /// Wraps a critical section and condition variable.
    /// </summary>
    internal sealed partial class LowLevelMonitor : IDisposable
    {
        private Interop.Kernel32.CRITICAL_SECTION _criticalSection;
        private Interop.Kernel32.CONDITION_VARIABLE _conditionVariable;

        public LowLevelMonitor()
        {
            Interop.Kernel32.InitializeCriticalSection(out _criticalSection);
            Interop.Kernel32.InitializeConditionVariable(out _conditionVariable);
        }

        private void DisposeCore()
        {
            Interop.Kernel32.DeleteCriticalSection(ref _criticalSection);
        }

        private void AcquireCore()
        {
            Interop.Kernel32.EnterCriticalSection(ref _criticalSection);
        }

        private void ReleaseCore()
        {
            Interop.Kernel32.LeaveCriticalSection(ref _criticalSection);
        }

        private void WaitCore()
        {
            WaitCore(-1);
        }

        private bool WaitCore(int timeoutMilliseconds)
        {
            bool waitResult = Interop.Kernel32.SleepConditionVariableCS(ref _conditionVariable, ref _criticalSection, timeoutMilliseconds);
            if (!waitResult)
            {
                int lastError = Marshal.GetLastWin32Error();
                if (lastError != Interop.Errors.ERROR_TIMEOUT)
                {
                    var exception = new OutOfMemoryException();
                    exception.HResult = lastError;
                    throw exception;
                }
            }
            return waitResult;
        }

        private void Signal_ReleaseCore()
        {
            Interop.Kernel32.WakeConditionVariable(ref _conditionVariable);
            Interop.Kernel32.LeaveCriticalSection(ref _criticalSection);
        }
    }
}