aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Common/PreciseSleep/SleepEvent.cs
blob: f0769d1e4c326b02f2f8fd7090944551445b69a5 (plain) (blame)
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
using System;
using System.Threading;

namespace Ryujinx.Common.PreciseSleep
{
    /// <summary>
    /// A cross-platform precise sleep event that has millisecond granularity.
    /// </summary>
    internal class SleepEvent : IPreciseSleepEvent
    {
        private readonly AutoResetEvent _waitEvent = new(false);

        public long AdjustTimePoint(long timePoint, long timeoutNs)
        {
            // No adjustment
            return timePoint;
        }

        public bool SleepUntil(long timePoint)
        {
            long now = PerformanceCounter.ElapsedTicks;
            long ms = Math.Min((timePoint - now) / PerformanceCounter.TicksPerMillisecond, int.MaxValue);

            if (ms > 0)
            {
                _waitEvent.WaitOne((int)ms);

                return true;
            }

            return false;
        }

        public void Sleep()
        {
            _waitEvent.WaitOne();
        }

        public void Signal()
        {
            _waitEvent.Set();
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);

            _waitEvent.Dispose();
        }
    }
}