Daily update on 20250316-095544 by Nitload Youmu. Additional Message : Linear math inmprovement
Signed-off-by: Nitload <YoumuLiu_NSI@whv0t.onmicrosoft.com>
This commit is contained in:
@@ -0,0 +1,164 @@
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
// file="TimeFunction.cs"
|
||||
// Project: StgSharp
|
||||
// AuthorGroup: Nitload Space
|
||||
// Copyright (c) Nitload Space. All rights reserved.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the “Software”), to deal in the Software without restriction,
|
||||
// including without limitation the rights to use, copy, modify, merge,
|
||||
// publish, distribute, sublicense, and/or sell copies of the Software,
|
||||
// and to permit persons to whom the Software is furnished to do so,
|
||||
// subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and
|
||||
// this permission notice shall be included in all copies
|
||||
// or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED “AS IS”,
|
||||
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
// ARISING FROM, OUT OF OR IN CONNECTION WITH
|
||||
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
//
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace StgSharp.Timing
|
||||
{
|
||||
public class TimeFunction
|
||||
{
|
||||
|
||||
private float _beginning, _ending;
|
||||
private Func<float, float> _timeRelatedCalculation;
|
||||
private TimeSpanProvider _timeProvider;
|
||||
|
||||
internal TimeFunction() { }
|
||||
|
||||
public TimeFunction(
|
||||
TimeSpanProvider timeSpanProvider,
|
||||
Func<float, float> timeRelatedCalculation,
|
||||
float range )
|
||||
{
|
||||
_timeProvider = timeSpanProvider;
|
||||
_timeRelatedCalculation = timeRelatedCalculation;
|
||||
if( timeSpanProvider == null ) {
|
||||
return;
|
||||
}
|
||||
_beginning = _timeProvider.CurrentSecond;
|
||||
_ending = _timeProvider.CurrentSecond + range;
|
||||
}
|
||||
|
||||
public virtual bool IsComplete
|
||||
{
|
||||
get => _timeProvider.CurrentSecond > _ending;
|
||||
}
|
||||
|
||||
public Func<float, float> TimeRelatedCalculation
|
||||
{
|
||||
get { return _timeRelatedCalculation; }
|
||||
set { _timeRelatedCalculation = value; }
|
||||
}
|
||||
|
||||
public static TimeFunction One
|
||||
{
|
||||
get => new TimeFunctionOne();
|
||||
}
|
||||
|
||||
public TimeSpanProvider TimeSpanProvider
|
||||
{
|
||||
get { return _timeProvider; }
|
||||
set { _timeProvider = value; }
|
||||
}
|
||||
|
||||
public virtual float Calculate()
|
||||
{
|
||||
if( _timeProvider.CurrentSecond < _ending ) {
|
||||
return 0;
|
||||
}
|
||||
return _timeRelatedCalculation(
|
||||
_timeProvider.CurrentSecond - _beginning );
|
||||
}
|
||||
|
||||
public static TimeFunction Proportional(
|
||||
TimeSpanProvider time,
|
||||
float begin,
|
||||
float range )
|
||||
{
|
||||
return new TimeFunction( time, ( float t ) => t + begin, range );
|
||||
}
|
||||
|
||||
public virtual TimeFunction Renew(
|
||||
(Func<float, float> func, float range) funcPair )
|
||||
{
|
||||
return new TimeFunction(
|
||||
_timeProvider, funcPair.func, funcPair.range );
|
||||
}
|
||||
|
||||
public virtual TimeFunction Renew(
|
||||
Func<float, float> func,
|
||||
float range )
|
||||
{
|
||||
return new TimeFunction( _timeProvider, func, range );
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
float range = _ending - _beginning;
|
||||
_beginning = _timeProvider.CurrentSecond;
|
||||
_ending = _beginning + range;
|
||||
}
|
||||
|
||||
public virtual TimeFunction Reverse()
|
||||
{
|
||||
float range = _ending - _beginning;
|
||||
return new TimeFunction(
|
||||
_timeProvider, p => _timeRelatedCalculation( range - p ),
|
||||
range );
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public sealed class TimeFunctionOne : TimeFunction
|
||||
{
|
||||
|
||||
internal TimeFunctionOne() : base() { }
|
||||
|
||||
public override bool IsComplete
|
||||
{
|
||||
get => true;
|
||||
}
|
||||
|
||||
public override float Calculate()
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
public override TimeFunction Renew(
|
||||
(Func<float, float> func, float range) funcPair )
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override TimeFunction Renew(
|
||||
Func<float, float> func,
|
||||
float range )
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
#pragma warning disable CA1822
|
||||
public new void Reset()
|
||||
#pragma warning restore CA1822
|
||||
{ }
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
// file="TimeProvider.cs"
|
||||
// Project: StgSharp
|
||||
// AuthorGroup: Nitload Space
|
||||
// Copyright (c) Nitload Space. All rights reserved.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the “Software”), to deal in the Software without restriction,
|
||||
// including without limitation the rights to use, copy, modify, merge,
|
||||
// publish, distribute, sublicense, and/or sell copies of the Software,
|
||||
// and to permit persons to whom the Software is furnished to do so,
|
||||
// subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and
|
||||
// this permission notice shall be included in all copies
|
||||
// or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED “AS IS”,
|
||||
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
// ARISING FROM, OUT OF OR IN CONNECTION WITH
|
||||
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
//
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
|
||||
using StgSharp.Timing;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace StgSharp
|
||||
{
|
||||
public static partial class StgSharp
|
||||
{
|
||||
|
||||
internal static StgSharpTime mainTimeProvider = new StgSharpTime();
|
||||
|
||||
internal static TimeSourceProviderBase MainTimeProvider => mainTimeProvider;
|
||||
|
||||
}
|
||||
|
||||
public sealed class StgSharpTime : TimeSourceProviderBase
|
||||
{
|
||||
|
||||
private static List<TimeSpanProvider> subscriberList = new List<TimeSpanProvider>(
|
||||
);
|
||||
private static long accuracy;
|
||||
private static Stopwatch mainProvider = new Stopwatch();
|
||||
private static Thread timeProvideThread;
|
||||
|
||||
internal StgSharpTime() { }
|
||||
|
||||
public static TimeSourceProviderBase OnlyInstance => StgSharp.MainTimeProvider;
|
||||
|
||||
public override sealed void StartProvidingTime()
|
||||
{
|
||||
if( mainProvider.IsRunning ) {
|
||||
return;
|
||||
}
|
||||
mainProvider.Start();
|
||||
|
||||
//speed test
|
||||
long totalMS, internalFrequncy = Stopwatch.Frequency;
|
||||
for( int i = 0; i < 100; i++ ) {
|
||||
totalMS = mainProvider.ElapsedTicks / ( internalFrequncy / ( 1000L * 1000L ) );
|
||||
for( int t = 0; t < 10; t++ ) {
|
||||
if( totalMS < 1000 ) {
|
||||
subscriberList.Add(
|
||||
new TimeSpanProvider(
|
||||
100L, TimeSpanProvider.DefaultProvider ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
mainProvider.Stop();
|
||||
subscriberList.Clear();
|
||||
totalMS = mainProvider.ElapsedTicks / ( internalFrequncy / ( 1000L * 1000L ) ) / 100L;
|
||||
accuracy = ( totalMS * 2 ) / 3;
|
||||
mainProvider.Reset();
|
||||
timeProvideThread = new Thread( new ThreadStart( ProvideTime ) );
|
||||
timeProvideThread.Start();
|
||||
}
|
||||
|
||||
public override void StopProvidingTime()
|
||||
{
|
||||
lock( mainProvider ) {
|
||||
mainProvider.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
public void Terminate()
|
||||
{
|
||||
lock( mainProvider ) {
|
||||
mainProvider.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
protected override sealed void AddSubscriberUnsynced(
|
||||
TimeSpanProvider subscriber )
|
||||
{
|
||||
subscriberList.Add( subscriber );
|
||||
}
|
||||
|
||||
protected override sealed void RemoveSubscriberUnsynced(
|
||||
TimeSpanProvider subscriber )
|
||||
{
|
||||
subscriberList.Remove( subscriber );
|
||||
}
|
||||
|
||||
private void ProvideTime()
|
||||
{
|
||||
long totalMS, internalFrequncy = Stopwatch.Frequency;
|
||||
lock( mainProvider ) {
|
||||
mainProvider.Restart();
|
||||
}
|
||||
while( mainProvider.IsRunning ) {
|
||||
totalMS = mainProvider.ElapsedTicks / ( internalFrequncy / ( 1000L * 1000L ) );
|
||||
if( subscriberList.Count == 0 ) {
|
||||
continue;
|
||||
}
|
||||
CheckSubscriberSemaphore.Wait();
|
||||
List<TimeSpanProvider> toRemoveList = new List<TimeSpanProvider>(
|
||||
);
|
||||
foreach( TimeSpanProvider subscriber in subscriberList ) {
|
||||
if( !subscriber.CheckTime( totalMS ) ) {
|
||||
toRemoveList.Add( subscriber );
|
||||
InternalIO.InternalWriteLog(
|
||||
$"Time subscriber {subscriber} is to be removed.",
|
||||
LogType.Info );
|
||||
}
|
||||
;
|
||||
}
|
||||
if( toRemoveList.Count != 0 ) {
|
||||
foreach( TimeSpanProvider subscriber in toRemoveList ) {
|
||||
subscriberList.Remove( subscriber );
|
||||
}
|
||||
}
|
||||
CheckSubscriberSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
// file="TimeSourceProvider.cs"
|
||||
// Project: StgSharp
|
||||
// AuthorGroup: Nitload Space
|
||||
// Copyright (c) Nitload Space. All rights reserved.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the “Software”), to deal in the Software without restriction,
|
||||
// including without limitation the rights to use, copy, modify, merge,
|
||||
// publish, distribute, sublicense, and/or sell copies of the Software,
|
||||
// and to permit persons to whom the Software is furnished to do so,
|
||||
// subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and
|
||||
// this permission notice shall be included in all copies
|
||||
// or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED “AS IS”,
|
||||
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
// ARISING FROM, OUT OF OR IN CONNECTION WITH
|
||||
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
//
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
using StgSharp;
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace StgSharp.Timing
|
||||
{
|
||||
public abstract class TimeSourceProviderBase
|
||||
{
|
||||
|
||||
private SemaphoreSlim _addSubscriberSemaphore = new SemaphoreSlim(
|
||||
1, 1 );
|
||||
|
||||
protected SemaphoreSlim CheckSubscriberSemaphore
|
||||
{
|
||||
get => _addSubscriberSemaphore;
|
||||
}
|
||||
|
||||
public void AddSubscriber( TimeSpanProvider subscriber )
|
||||
{
|
||||
try {
|
||||
_addSubscriberSemaphore.Wait();
|
||||
AddSubscriberUnsynced( subscriber );
|
||||
}
|
||||
catch( Exception ) {
|
||||
throw;
|
||||
}
|
||||
finally {
|
||||
_addSubscriberSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveSubscriber( TimeSpanProvider subscriber )
|
||||
{
|
||||
_addSubscriberSemaphore.Wait();
|
||||
try {
|
||||
RemoveSubscriberUnsynced( subscriber );
|
||||
}
|
||||
catch( Exception ) {
|
||||
throw;
|
||||
}
|
||||
finally {
|
||||
_addSubscriberSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public abstract void StartProvidingTime();
|
||||
|
||||
public abstract void StopProvidingTime();
|
||||
|
||||
protected abstract void AddSubscriberUnsynced(
|
||||
TimeSpanProvider subscriber );
|
||||
|
||||
protected abstract void RemoveSubscriberUnsynced(
|
||||
TimeSpanProvider subscriber );
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
// file="TimeSpanAwaitingToken.cs"
|
||||
// Project: StgSharp
|
||||
// AuthorGroup: Nitload Space
|
||||
// Copyright (c) Nitload Space. All rights reserved.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the “Software”), to deal in the Software without restriction,
|
||||
// including without limitation the rights to use, copy, modify, merge,
|
||||
// publish, distribute, sublicense, and/or sell copies of the Software,
|
||||
// and to permit persons to whom the Software is furnished to do so,
|
||||
// subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and
|
||||
// this permission notice shall be included in all copies
|
||||
// or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED “AS IS”,
|
||||
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
// ARISING FROM, OUT OF OR IN CONNECTION WITH
|
||||
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
//
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace StgSharp.Timing
|
||||
{
|
||||
#nullable enable
|
||||
|
||||
public sealed class TimeSpanAwaitingToken : IDisposable
|
||||
{
|
||||
|
||||
private static readonly ConcurrentStack<int> s_unusedID = new ConcurrentStack<int>(
|
||||
[0] );
|
||||
private static int s_maxID;
|
||||
private static readonly object s_lock = new object();
|
||||
|
||||
private EventHandler? _refreshHandler,_missHandler;
|
||||
private int _size, _id;
|
||||
|
||||
private object _participantObject = new object();
|
||||
private SemaphoreSlim _awaitingSemaphore;
|
||||
|
||||
private TimeSpanProvider _provider;
|
||||
|
||||
internal TimeSpanAwaitingToken( TimeSpanProvider provider )
|
||||
{
|
||||
if( s_unusedID.Count == 1 ) {
|
||||
lock( s_lock ) {
|
||||
s_unusedID.TryPop( out int id );
|
||||
TokenID = id;
|
||||
s_unusedID.Push( s_maxID++ );
|
||||
}
|
||||
} else {
|
||||
s_unusedID.TryPop( out int id );
|
||||
TokenID = id;
|
||||
}
|
||||
_provider = provider;
|
||||
_size = 1;
|
||||
_awaitingSemaphore = new SemaphoreSlim( 0, 1 );
|
||||
}
|
||||
|
||||
internal TimeSpanAwaitingToken( TimeSpanProvider provider, int count )
|
||||
{
|
||||
if( s_unusedID.Count == 1 ) {
|
||||
lock( s_lock ) {
|
||||
s_unusedID.TryPop( out int id );
|
||||
TokenID = id;
|
||||
s_unusedID.Push( s_maxID++ );
|
||||
}
|
||||
} else {
|
||||
s_unusedID.TryPop( out int id );
|
||||
TokenID = id;
|
||||
}
|
||||
_provider = provider;
|
||||
_size = count;
|
||||
_awaitingSemaphore = new SemaphoreSlim( 0, _size );
|
||||
}
|
||||
|
||||
public event EventHandler MissTimeSpanRefreshed
|
||||
{
|
||||
add { _missHandler += value; }
|
||||
remove { _missHandler -= value; }
|
||||
}
|
||||
|
||||
public event EventHandler TimeSpanRefreshed
|
||||
{
|
||||
add { _refreshHandler += value; }
|
||||
remove { _refreshHandler -= value; }
|
||||
}
|
||||
|
||||
public int TokenID
|
||||
{
|
||||
get => _id;
|
||||
private set => _id = value;
|
||||
}
|
||||
|
||||
internal SemaphoreSlim AwaitingSemaphoreSlim
|
||||
{
|
||||
get => _awaitingSemaphore;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_provider.QuitSpanAwaiting( this );
|
||||
s_unusedID.Push( TokenID );
|
||||
_awaitingSemaphore.Dispose();
|
||||
GC.SuppressFinalize( this );
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return _id;
|
||||
}
|
||||
|
||||
public void Participant()
|
||||
{
|
||||
lock( _participantObject ) {
|
||||
_size++;
|
||||
SemaphoreSlim newSemaphore = new SemaphoreSlim(
|
||||
_awaitingSemaphore.CurrentCount, _size );
|
||||
Interlocked.Exchange( ref _awaitingSemaphore, newSemaphore )
|
||||
.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void WaitNextSpan()
|
||||
{
|
||||
_awaitingSemaphore.Wait();
|
||||
}
|
||||
|
||||
internal void MissRefresh()
|
||||
{
|
||||
_missHandler?.Invoke( this, EventArgs.Empty );
|
||||
}
|
||||
|
||||
[MethodImpl( MethodImplOptions.AggressiveInlining )]
|
||||
internal void Refresh()
|
||||
{
|
||||
_refreshHandler?.Invoke( this, EventArgs.Empty );
|
||||
}
|
||||
|
||||
~TimeSpanAwaitingToken()
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
|
||||
}
|
||||
#nullable restore
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
// file="TimeSpanProvider.cs"
|
||||
// Project: StgSharp
|
||||
// AuthorGroup: Nitload Space
|
||||
// Copyright (c) Nitload Space. All rights reserved.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person
|
||||
// obtaining a copy of this software and associated documentation
|
||||
// files (the “Software”), to deal in the Software without restriction,
|
||||
// including without limitation the rights to use, copy, modify, merge,
|
||||
// publish, distribute, sublicense, and/or sell copies of the Software,
|
||||
// and to permit persons to whom the Software is furnished to do so,
|
||||
// subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and
|
||||
// this permission notice shall be included in all copies
|
||||
// or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED “AS IS”,
|
||||
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
// ARISING FROM, OUT OF OR IN CONNECTION WITH
|
||||
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
//
|
||||
//-----------------------------------------------------------------------
|
||||
//-----------------------------------------------------------------------
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace StgSharp.Timing
|
||||
{
|
||||
/// <summary>
|
||||
/// A microsecond-accuracy timer. It will refresh every a certain time span.
|
||||
/// </summary>
|
||||
public class TimeSpanProvider
|
||||
{
|
||||
|
||||
private bool _subscribed;
|
||||
|
||||
private ConcurrentQueue<TimeSpanAwaitingToken> _tokenToAdd = new ConcurrentQueue<TimeSpanAwaitingToken>(
|
||||
);
|
||||
private ConcurrentQueue<TimeSpanAwaitingToken> _tokenToQuit;
|
||||
private Counter<int> timeSpanCount = new Counter<int>( -1, 1, 1 );
|
||||
private HashSet<TimeSpanAwaitingToken> _awaitingTokens;
|
||||
private long _maxSpanCount;
|
||||
private long _spanBegin;
|
||||
private readonly long _spanLength;
|
||||
private readonly TimeSourceProviderBase _timeSource;
|
||||
|
||||
/// <summary>
|
||||
/// Create a new <see cref="TimeSpanProvider" /> and define the length of time span. Length
|
||||
/// of a single time span is defined in microseconds.
|
||||
/// </summary>
|
||||
/// <param _name="spanMicroSeconds"></param>
|
||||
/// <param _name="provider"></param>
|
||||
public TimeSpanProvider(
|
||||
long spanMicroSeconds,
|
||||
TimeSourceProviderBase provider )
|
||||
{
|
||||
if( provider == null ) {
|
||||
throw new ArgumentNullException( nameof( provider ) );
|
||||
}
|
||||
_timeSource = provider;
|
||||
_spanLength = spanMicroSeconds;
|
||||
_maxSpanCount = int.MaxValue;
|
||||
provider.AddSubscriber( this );
|
||||
_subscribed = true;
|
||||
_awaitingTokens = new HashSet<TimeSpanAwaitingToken>();
|
||||
_tokenToQuit = new ConcurrentQueue<TimeSpanAwaitingToken>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new <see cref="TimeSpanProvider" /> and define the length of time span. Length
|
||||
/// of a single time span is defined in seconds.
|
||||
/// </summary>
|
||||
/// <param _name="spanSeconds"></param>
|
||||
/// <param _name="provider"></param>
|
||||
public TimeSpanProvider(
|
||||
double spanSeconds,
|
||||
TimeSourceProviderBase provider )
|
||||
{
|
||||
if( provider == null ) {
|
||||
throw new ArgumentNullException( nameof( provider ) );
|
||||
}
|
||||
_timeSource = provider;
|
||||
_spanLength = ( long )( spanSeconds * 1000L * 1000L );
|
||||
_spanBegin = -_spanLength;
|
||||
_maxSpanCount = long.MaxValue;
|
||||
provider.AddSubscriber( this );
|
||||
_subscribed = true;
|
||||
_awaitingTokens = new HashSet<TimeSpanAwaitingToken>();
|
||||
_tokenToQuit = new ConcurrentQueue<TimeSpanAwaitingToken>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a new <see cref="TimeSpanProvider" /> and define the length of time span. Length
|
||||
/// of a single time span is defined in microseconds.
|
||||
/// </summary>
|
||||
/// <param _name="spanLength"></param>
|
||||
/// <param _name="maxSpan"></param>
|
||||
/// <param _name="provider"></param>
|
||||
public TimeSpanProvider(
|
||||
long spanLength,
|
||||
long maxSpan,
|
||||
TimeSourceProviderBase provider )
|
||||
{
|
||||
if( provider == null ) {
|
||||
throw new ArgumentNullException( nameof( provider ) );
|
||||
}
|
||||
if( maxSpan <= 0 ) {
|
||||
throw new ArgumentException(
|
||||
"Sapn count cannot be smaller than zero" );
|
||||
}
|
||||
_timeSource = provider;
|
||||
_spanLength = spanLength;
|
||||
_spanBegin = -_spanLength;
|
||||
provider.AddSubscriber( this );
|
||||
_subscribed = true;
|
||||
_awaitingTokens = new HashSet<TimeSpanAwaitingToken>();
|
||||
_tokenToQuit = new ConcurrentQueue<TimeSpanAwaitingToken>();
|
||||
}
|
||||
|
||||
public double SpanLength
|
||||
{
|
||||
get => ( _spanLength * 1.0 ) / ( 1000L * 1000L );
|
||||
}
|
||||
|
||||
public float CurrentSecond
|
||||
{
|
||||
get => timeSpanCount.Value * SpanLengthLowPrecession;
|
||||
}
|
||||
|
||||
public float SpanLengthLowPrecession
|
||||
{
|
||||
get => ( _spanLength * 1.0f ) / ( 1000 * 1000 );
|
||||
}
|
||||
|
||||
public int CurrentSpan
|
||||
{
|
||||
get => timeSpanCount.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Time source provider provided in <see cref="StgSharp" /> internal framework.
|
||||
/// </summary>
|
||||
public static TimeSourceProviderBase DefaultProvider => StgSharpTime.OnlyInstance;
|
||||
|
||||
public TimeSpanAwaitingToken ParticipantSpanAwaiting( int count )
|
||||
{
|
||||
TimeSpanAwaitingToken token = new TimeSpanAwaitingToken(
|
||||
this, count );
|
||||
_tokenToAdd.Enqueue( token );
|
||||
return token;
|
||||
}
|
||||
|
||||
public void QuitSpanAwaiting( TimeSpanAwaitingToken token )
|
||||
{
|
||||
_tokenToQuit.Enqueue( token );
|
||||
}
|
||||
|
||||
public void StopSpanProviding()
|
||||
{
|
||||
Interlocked.Exchange( ref _maxSpanCount, 0 );
|
||||
}
|
||||
|
||||
public void SubscribeToTimeSource(
|
||||
TimeSourceProviderBase serviceHandler )
|
||||
{
|
||||
if( serviceHandler == null ) {
|
||||
throw new ArgumentNullException( nameof( serviceHandler ) );
|
||||
}
|
||||
if( _subscribed ) {
|
||||
return;
|
||||
}
|
||||
_subscribed = true;
|
||||
serviceHandler.AddSubscriber( this );
|
||||
}
|
||||
|
||||
public int ToInt32()
|
||||
{
|
||||
return timeSpanCount.Value;
|
||||
}
|
||||
|
||||
internal bool CheckTime( long microseconds )
|
||||
{
|
||||
if( microseconds - _spanBegin < _spanLength ) {
|
||||
return true;
|
||||
}
|
||||
while( !_tokenToAdd.IsEmpty ) {
|
||||
_tokenToAdd.TryDequeue( out TimeSpanAwaitingToken tokenAdd );
|
||||
_awaitingTokens.Add( tokenAdd );
|
||||
}
|
||||
while( !_tokenToQuit.IsEmpty ) {
|
||||
_tokenToQuit.TryDequeue( out TimeSpanAwaitingToken tokenQuit );
|
||||
_awaitingTokens.Remove( tokenQuit );
|
||||
InternalIO.InternalWriteLog(
|
||||
$"Awaiting token {tokenQuit!.TokenID} has been removed.",
|
||||
LogType.Info );
|
||||
}
|
||||
|
||||
_spanBegin = microseconds;
|
||||
timeSpanCount++;
|
||||
|
||||
foreach( TimeSpanAwaitingToken item in _awaitingTokens ) {
|
||||
if( item.AwaitingSemaphoreSlim.CurrentCount == 0 ) {
|
||||
item.AwaitingSemaphoreSlim.Release();
|
||||
item.Refresh();
|
||||
} else {
|
||||
item.MissRefresh();
|
||||
}
|
||||
}
|
||||
|
||||
return timeSpanCount < _maxSpanCount;
|
||||
}
|
||||
|
||||
public static explicit operator int(
|
||||
[NotNull]TimeSpanProvider provider )
|
||||
{
|
||||
return provider.ToInt32();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user