feat(timers): Adds timer pooling, fixes timer related bugs, and changes timer api (#667)

### Changes/Fixes:
* Adds timer pooling.
* Allows pool to be configurable in ModernUO.json
* Pool replenishes itself asynchronously if depleted.
* Fixes an issue with barkeeps and town criers
* Fixes an issue with incognito buff icons not being removed
* Fixes an issue with polymorph name mod not being removed
* Fixes several places where timers go on forever even after an object is deleted, keeping a reference (memory leak)
* Eliminates the timer for MiningCart altogether.
* Deletes `AcidSlime` since it is a duplicate of `PoolOfAcid`
* Fixes HonorableExecution and standardizes the code for other Bushido moves.

## Changes to the Timer API:
```cs
public class Timer
{
  // Creates a timer that will be returned to the pool once execution stops.
  public static void StartTimer(Action callback);
  public static void StartTimer(TimeSpan delay, Action callback);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback);
  public static void StartTimer(TimeSpan interval, int count, Action callback);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback);

  // Creates a timer and returns a token for more control. Requires manual cancellation in order for the timer to be returned to the pool.
  // If the token is dereferenced, the timer will be dereferenced too. While not returning a timer to the pool is not considered hazardous, it does defeat the purpose of pooled timers.
  public static void StartTimer(Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan interval, int count, Action callback, out TimerExecutionToken token);
  public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback, out TimerExecutionToken token);

  // If you aren't sure how to use the API above, or you don't care about performance, then you can use the old RunUO Timer.DelayCall
  public static DelayCallTimer DelayCall(Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan interval, int count, Action callback);
  public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, int count, Action callback);
}

public struct TimerExecutionToken
{
  public bool Running { get; }
  public int Index { get; }
  public int RemainingCount { get; }
  public DateTime Next { get; }
}
```

## When to use `TimerExecutionToken`?
Use tokens when you want to gain the performance benefit of using a pooled timer, but you need one of the following:
* Access to the next time the timer will tick:`token.Next`
* Access to which interval, how many intervals there are, or how many are remaining: `token.Index`, `token.Count`, and `token.RemainingCount`
* Stop a timer manually.
* Determine if the timer is running: `timer.Running`
* See notes below about requirements for using tokens!

## Notes about using the TimerExecutionToken:
When you opt-in to receive a token, you must call `Cancel()` to return the timer. This can be done inside of the callback, or outside of the callback at any time.
If this is not called and your timer is an infinite interval, then you will create a potential memory leak, or null pointer exception in your callback.
If the timer ends and is stopped, but cancel is not called, then the timer will never return to the pool and stay referenced until the token is deleted or cancel is called. (Memory leak)

## Is this thread safe?
No. The ModernUO timer system is not thread safe at all. If you require a thread safe timer system, contact me and I'll help adapt this system. Keep in mind that there is a massive performance hit to make this thread safe when there are literally no use cases for it.

If you need to synchronize execution, meaning you want to execute code from another thread on the core thread. Let's say you have a discord bot that is pushing commands to the game server. Then use `EventLoopContext.Post(SendOrPostCallback callback, object state);`.
This commit is contained in:
Kamron Batman 2021-08-07 14:33:35 -07:00 • committed by GitHub
parent b4de631f96
commit 9b554f69b0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
219 changed files with 1897 additions and 2241 deletions

View file

@ -32,6 +32,8 @@ namespace Server
public override SynchronizationContext CreateCopy() => new EventLoopContext();
public void Post(Action d) => _queue.Enqueue(d);
public override void Post(SendOrPostCallback d, object state) => _queue.Enqueue(() => d(state));
public override void Send(SendOrPostCallback d, object state)

View file

@ -108,7 +108,7 @@ namespace Server
public void Deserialize(IGenericReader reader)
{
// Should not actually be saved
Timer.DelayCall(Delete);
Timer.StartTimer(Delete);
}
public void Serialize(IGenericWriter writer)

View file

@ -3027,7 +3027,7 @@ namespace Server
if (HeldBy != null)
{
Timer.DelayCall(FixHolding_Sandbox);
Timer.StartTimer(FixHolding_Sandbox);
}
// if (version < 9)

View file

@ -47,7 +47,7 @@ namespace Server
private static int _itemCount;
private static int _mobileCount;
private static EventLoopContext _eventLoopContext;
public static EventLoopContext LoopContext { get; set; }
private static readonly Type[] _serialTypeArray = { typeof(Serial) };
@ -366,9 +366,9 @@ namespace Server
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
_eventLoopContext = new EventLoopContext();
LoopContext = new EventLoopContext();
SynchronizationContext.SetSynchronizationContext(_eventLoopContext);
SynchronizationContext.SetSynchronizationContext(LoopContext);
foreach (var a in args)
{
@ -505,7 +505,9 @@ namespace Server
events += NetState.Slice();
// Execute captured post-await methods (like Timer.Pause)
events += _eventLoopContext.ExecuteTasks();
events += LoopContext.ExecuteTasks();
Timer.CheckTimerPool(); // Check for pool depletion so we can async refill it.
_tickCount = 0;
_now = DateTime.MinValue;

View file

@ -454,7 +454,7 @@ namespace Server
private List<object> _actions;
private AccessLevel m_AccessLevel;
private Timer m_AutoManifestTimer;
private TimerExecutionToken _autoManifestTimerToken;
private Container m_Backpack;
@ -465,7 +465,7 @@ namespace Server
private int m_ChangingCombatant;
private Mobile m_Combatant;
private Timer m_CombatTimer;
private TimerExecutionToken _combatTimerToken;
private ContextMenu m_ContextMenu;
private bool m_Criminal;
@ -473,14 +473,15 @@ namespace Server
private Direction m_Direction;
private bool m_DisplayGuildTitle;
private Timer m_ExpireAggrTimer;
private Timer m_ExpireCombatant;
private TimerExecutionToken _expireAggrTimerToken;
private TimerExecutionToken _expireCombatantTimerToken;
private TimerExecutionToken _expireCriminalTimerToken;
private FacialHairInfo m_FacialHair;
private int m_Fame, m_Karma;
private bool m_Female, m_Warmode, m_Hidden, m_Blessed, m_Flying;
private int m_Followers, m_FollowersMax;
private bool m_Frozen;
private Timer m_FrozenTimer;
private TimerExecutionToken _frozenTimerToken;
private BaseGuild m_Guild;
private string m_GuildTitle;
@ -498,7 +499,7 @@ namespace Server
private string m_Language;
private int m_LightLevel;
private Point3D m_Location;
private Timer m_LogoutTimer;
private TimerExecutionToken _logoutTimerToken;
private Timer m_ManaTimer, m_HitsTimer, m_StamTimer;
private Map m_Map;
@ -525,7 +526,7 @@ namespace Server
private NetState m_NetState;
private DateTime m_NextWarmodeChange;
private bool m_Paralyzed;
private Timer m_ParaTimer;
private TimerExecutionToken _paraTimerToken;
private bool m_Player;
private Poison m_Poison;
private Prompt m_Prompt;
@ -546,7 +547,7 @@ namespace Server
private int m_VirtualArmor;
private int m_VirtualArmorMod;
private int m_WarmodeChanges;
private WarmodeTimer m_WarmodeTimer;
private bool _warmodeSpamValue;
private IWeapon m_Weapon;
private bool m_YellowHealthbar;
@ -768,12 +769,7 @@ namespace Server
Delta(MobileDelta.Flags);
SendLocalizedMessage(m_Paralyzed ? 502381 : 502382);
if (m_ParaTimer != null)
{
m_ParaTimer.Stop();
m_ParaTimer = null;
}
_paraTimerToken.Cancel();
}
}
}
@ -794,12 +790,7 @@ namespace Server
{
m_Frozen = value;
Delta(MobileDelta.Flags);
if (m_FrozenTimer != null)
{
m_FrozenTimer.Stop();
m_FrozenTimer = null;
}
_frozenTimerToken.Cancel();
}
}
}
@ -880,7 +871,11 @@ namespace Server
public bool ChangingCombatant => m_ChangingCombatant > 0;
private void ExpireCombatant() => Combatant = null;
private void ExpireCombatant()
{
Combatant = null;
_expireCombatantTimerToken.Cancel();
}
/// <summary>
/// Overridable. Gets or sets which Mobile that this Mobile is currently engaged in combat with.
@ -915,20 +910,14 @@ namespace Server
if (m_Combatant == null)
{
m_NetState.SendChangeCombatant(Serial.Zero);
m_ExpireCombatant?.Stop();
m_CombatTimer?.Stop();
m_ExpireCombatant = null;
m_CombatTimer = null;
_expireCombatantTimerToken.Cancel();
_combatTimerToken.Cancel();
}
else
{
m_NetState.SendChangeCombatant(m_Combatant.Serial);
m_ExpireCombatant ??= Timer.DelayCall(ExpireCombatantDelay, ExpireCombatant);
m_ExpireCombatant.Start();
m_CombatTimer ??= new CombatTimer(this);
m_CombatTimer.Start();
Timer.StartTimer(ExpireCombatantDelay, ExpireCombatant, out _expireCombatantTimerToken);
Timer.StartTimer(TimeSpan.FromSeconds(0.01), 0, CheckCombatTime, out _combatTimerToken);
if (CanBeHarmful(m_Combatant, false))
{
@ -943,6 +932,40 @@ namespace Server
}
}
private void CheckCombatTime()
{
if (Core.TickCount - NextCombatTime < 0)
{
return;
}
var combatant = Combatant;
// If no combatant, wrong map, one of us is a ghost, or cannot see, or deleted, then stop combat
if (combatant?.Deleted != false || Deleted || combatant.m_Map != m_Map ||
!combatant.Alive || !Alive || !CanSee(combatant) || combatant.IsDeadBondedPet ||
IsDeadBondedPet)
{
Combatant = null;
return;
}
var weapon = Weapon;
if (!InRange(combatant, weapon.MaxRange))
{
return;
}
if (InLOS(combatant))
{
weapon.OnBeforeSwing(this, combatant);
RevealingAction();
NextCombatTime =
Core.TickCount + (int)weapon.OnSwing(this, combatant).TotalMilliseconds;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int TotalGold => GetTotal(TotalType.Gold);
@ -1347,11 +1370,7 @@ namespace Server
if (m_Warmode != value)
{
if (m_AutoManifestTimer != null)
{
m_AutoManifestTimer.Stop();
m_AutoManifestTimer = null;
}
_autoManifestTimerToken.Cancel();
m_Warmode = value;
Delta(MobileDelta.Flags);
@ -1439,6 +1458,7 @@ namespace Server
}
m_NetState = value;
_logoutTimerToken.Cancel();
if (m_NetState == null)
{
@ -1446,27 +1466,13 @@ namespace Server
EventSink.InvokeDisconnected(this);
// Disconnected, start the logout timer
if (m_LogoutTimer == null)
{
m_LogoutTimer = Timer.DelayCall(GetLogoutDelay(), Logout);
}
else
{
m_LogoutTimer.Stop();
m_LogoutTimer.Delay = GetLogoutDelay();
m_LogoutTimer.Start();
}
Timer.StartTimer(GetLogoutDelay(), Logout, out _logoutTimerToken);
}
else
{
OnConnected();
EventSink.InvokeConnected(this);
// Connected, stop the logout timer and if needed, move to the world
m_LogoutTimer?.Stop();
m_LogoutTimer = null;
if (m_Map == Map.Internal && LogoutMap != null)
{
Map = LogoutMap;
@ -1494,7 +1500,7 @@ namespace Server
}
}
Timer.DelayCall(item.Delete);
Timer.StartTimer(item.Delete);
}
}
@ -1852,8 +1858,6 @@ namespace Server
}
}
public Timer ExpireCriminalTimer { get; set; }
[CommandProperty(AccessLevel.Counselor, AccessLevel.GameMaster)]
public virtual bool Criminal
{
@ -1867,23 +1871,11 @@ namespace Server
InvalidateProperties();
}
_expireCriminalTimerToken.Cancel();
if (m_Criminal)
{
if (ExpireCriminalTimer == null)
{
ExpireCriminalTimer = Timer.DelayCall(ExpireCriminalDelay, ExpireCriminal);
}
else
{
ExpireCriminalTimer.Stop();
}
ExpireCriminalTimer.Start();
}
else if (ExpireCriminalTimer != null)
{
ExpireCriminalTimer.Stop();
ExpireCriminalTimer = null;
Timer.StartTimer(ExpireCriminalDelay, ExpireCriminal, out _expireCriminalTimerToken);
}
}
}
@ -3545,10 +3537,9 @@ namespace Server
{
StopAggrExpire();
}
else if (m_ExpireAggrTimer == null)
else if (!_expireAggrTimerToken.Running)
{
m_ExpireAggrTimer = Timer.DelayCall(ExpireAggressorsDelay, ExpireAggressorsDelay, ExpireAggr);
m_ExpireAggrTimer.Start();
Timer.StartTimer(ExpireAggressorsDelay, ExpireAggressorsDelay, ExpireAggr, out _expireAggrTimerToken);
}
}
@ -3566,8 +3557,7 @@ namespace Server
private void StopAggrExpire()
{
m_ExpireAggrTimer?.Stop();
m_ExpireAggrTimer = null;
_expireAggrTimerToken.Cancel();
}
private void CheckAggrExpire()
@ -3712,9 +3702,10 @@ namespace Server
public void DelayChangeWarmode(bool value)
{
if (m_WarmodeTimer != null)
if (m_WarmodeChanges > WarmodeCatchCount)
{
m_WarmodeTimer.Value = value;
_warmodeSpamValue = value;
m_WarmodeChanges++;
return;
}
@ -3731,21 +3722,21 @@ namespace Server
m_WarmodeChanges = 1;
m_NextWarmodeChange = now + WarmodeSpamCatch;
}
else if (m_WarmodeChanges == WarmodeCatchCount)
else if (m_WarmodeChanges++ == WarmodeCatchCount)
{
m_WarmodeTimer = new WarmodeTimer(this, value);
m_WarmodeTimer.Start();
Timer.StartTimer(WarmodeSpamDelay, WarmodeSpamTimeout);
return;
}
else
{
++m_WarmodeChanges;
}
Warmode = value;
}
private void WarmodeSpamTimeout()
{
Warmode = _warmodeSpamValue;
m_WarmodeChanges = 0;
}
public bool InLOS(Mobile target) =>
!Deleted && m_Map != null &&
(target == this || m_AccessLevel > AccessLevel.Player || m_Map.LineOfSight(this, target));
@ -3808,9 +3799,7 @@ namespace Server
if (!m_Paralyzed)
{
Paralyzed = true;
m_ParaTimer = Timer.DelayCall(duration, ExpireParalyzed);
m_ParaTimer.Start();
Timer.StartTimer(duration, ExpireParalyzed, out _paraTimerToken);
}
}
@ -3824,9 +3813,7 @@ namespace Server
if (!m_Frozen)
{
Frozen = true;
m_FrozenTimer = Timer.DelayCall(duration, ExpireFrozen);
m_FrozenTimer.Start();
Timer.StartTimer(duration, ExpireFrozen, out _frozenTimerToken);
}
}
@ -3938,16 +3925,8 @@ namespace Server
if (Combatant == aggressor)
{
if (m_ExpireCombatant == null)
{
m_ExpireCombatant = Timer.DelayCall(ExpireCombatantDelay, ExpireCombatant);
}
else
{
m_ExpireCombatant.Stop();
}
m_ExpireCombatant.Start();
_expireCombatantTimerToken.Cancel();
Timer.StartTimer(ExpireCombatantDelay, ExpireCombatant, out _expireCombatantTimerToken);
}
var addAggressor = true;
@ -4787,14 +4766,13 @@ namespace Server
m_HitsTimer?.Stop();
m_StamTimer?.Stop();
m_ManaTimer?.Stop();
m_CombatTimer?.Stop();
m_ExpireCombatant?.Stop();
m_LogoutTimer?.Stop();
ExpireCriminalTimer?.Stop();
m_WarmodeTimer?.Stop();
m_ParaTimer?.Stop();
m_FrozenTimer?.Stop();
m_AutoManifestTimer?.Stop();
_combatTimerToken.Cancel();
_expireCombatantTimerToken.Cancel();
_logoutTimerToken.Cancel();
_expireCriminalTimerToken.Cancel();
_paraTimerToken.Cancel();
_frozenTimerToken.Cancel();
_autoManifestTimerToken.Cancel();
}
public virtual bool AllowSkillUse(SkillName name) => true;
@ -4864,15 +4842,11 @@ namespace Server
if (Paralyzed)
{
Paralyzed = false;
m_ParaTimer?.Stop();
}
if (Frozen)
{
Frozen = false;
m_FrozenTimer?.Stop();
}
var content = new List<Item>();
@ -5570,17 +5544,8 @@ namespace Server
public virtual void Manifest(TimeSpan delay)
{
Warmode = true;
if (m_AutoManifestTimer == null)
{
m_AutoManifestTimer = Timer.DelayCall(delay, AutoManifest);
}
else
{
m_AutoManifestTimer.Stop();
}
m_AutoManifestTimer.Start();
_autoManifestTimerToken.Cancel();
Timer.StartTimer(delay, AutoManifest, out _autoManifestTimerToken);
}
public virtual bool CheckSpeechManifest()
@ -5592,7 +5557,7 @@ namespace Server
var delay = AutoManifestTimeout;
if (delay > TimeSpan.Zero && (!Warmode || m_AutoManifestTimer != null))
if (delay > TimeSpan.Zero && (!Warmode || _autoManifestTimerToken.Running))
{
Manifest(delay);
return true;
@ -6548,8 +6513,7 @@ namespace Server
if (m_Criminal)
{
ExpireCriminalTimer ??= Timer.DelayCall(ExpireCriminalDelay, ExpireCriminal);
ExpireCriminalTimer.Start();
Timer.StartTimer(ExpireCriminalDelay, ExpireCriminal, out _expireCriminalTimerToken);
}
if (ShouldCheckStatTimers)
@ -8186,27 +8150,6 @@ namespace Server
{
}
private class WarmodeTimer : Timer
{
private Mobile m_Mobile;
public WarmodeTimer(Mobile m, bool value) : base(WarmodeSpamDelay)
{
m_Mobile = m;
Value = value;
}
public bool Value{ get; set; }
protected override void OnTick()
{
m_Mobile.Warmode = Value;
m_Mobile.m_WarmodeChanges = 0;
m_Mobile.m_WarmodeTimer = null;
}
}
public static TimeSpan GetHitsRegenRate(Mobile m) => HitsRegenRateHandler?.Invoke(m) ?? DefaultHitsRate;
public static TimeSpan GetStamRegenRate(Mobile m) => StamRegenRateHandler?.Invoke(m) ?? DefaultStamRate;
@ -8588,16 +8531,8 @@ namespace Server
Combatant = target;
}
if (m_ExpireCombatant == null)
{
m_ExpireCombatant = Timer.DelayCall(ExpireCombatantDelay, ExpireCombatant);
}
else
{
m_ExpireCombatant.Stop();
}
m_ExpireCombatant.Start();
_expireCombatantTimerToken.Cancel();
Timer.StartTimer(ExpireCombatantDelay, ExpireCombatant, out _expireCombatantTimerToken);
}
public virtual bool HarmfulCheck(Mobile target)
@ -9446,48 +9381,6 @@ namespace Server
}
}
private class CombatTimer : Timer
{
private readonly Mobile m_Mobile;
public CombatTimer(Mobile m) : base(TimeSpan.FromSeconds(0.0), TimeSpan.FromSeconds(0.01)) =>
m_Mobile = m;
protected override void OnTick()
{
if (Core.TickCount - m_Mobile.NextCombatTime < 0)
{
return;
}
var combatant = m_Mobile.Combatant;
// If no combatant, wrong map, one of us is a ghost, or cannot see, or deleted, then stop combat
if (combatant?.Deleted != false || m_Mobile.Deleted || combatant.m_Map != m_Mobile.m_Map ||
!combatant.Alive || !m_Mobile.Alive || !m_Mobile.CanSee(combatant) || combatant.IsDeadBondedPet ||
m_Mobile.IsDeadBondedPet)
{
m_Mobile.Combatant = null;
return;
}
var weapon = m_Mobile.Weapon;
if (!m_Mobile.InRange(combatant, weapon.MaxRange))
{
return;
}
if (m_Mobile.InLOS(combatant))
{
weapon.OnBeforeSwing(m_Mobile, combatant);
m_Mobile.RevealingAction();
m_Mobile.NextCombatTime =
Core.TickCount + (int)weapon.OnSwing(m_Mobile, combatant).TotalMilliseconds;
}
}
}
private void ExpireCriminal()
{
Criminal = false;

View file

@ -124,7 +124,7 @@ namespace Server.Network
public static void Initialize()
{
Timer.DelayCall(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1.5), CheckAllAlive);
Timer.StartTimer(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1.5), CheckAllAlive);
}
public NetState(ISocket connection)

View file

@ -138,8 +138,8 @@ namespace Server
ns?.RemoveTrade(this);
Timer.DelayCall(From.Dispose);
Timer.DelayCall(To.Dispose);
Timer.StartTimer(From.Dispose);
Timer.StartTimer(To.Dispose);
}
public void UpdateFromCurrency()

View file

@ -14,252 +14,222 @@
*************************************************************************/
using System;
#if DEBUG_TIMERS
using System.Collections.Generic;
#endif
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Server
{
public delegate void TimerStateCallback<in T>(T state);
public delegate void TimerStateCallback<in T1, in T2>(T1 t1, T2 t2);
public delegate void TimerStateCallback<in T1, in T2, in T3>(T1 t1, T2 t2, T3 t3);
public delegate void TimerStateCallback<in T1, in T2, in T3, in T4>(T1 t1, T2 t2, T3 t3, T4 t4);
public partial class Timer
{
private static string FormatDelegate(Delegate callback) =>
callback == null ? "null" : $"{callback.Method.DeclaringType?.FullName ?? ""}.{callback.Method.Name}";
public static Timer DelayCall(Action callback) => DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(Action callback) => DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback);
public static Timer DelayCall(TimeSpan delay, Action callback) =>
DelayCall(delay, TimeSpan.Zero, 1, callback);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(TimeSpan delay, Action callback) => DelayCall(delay, TimeSpan.Zero, 1, callback);
public static Timer DelayCall(TimeSpan delay, TimeSpan interval, Action callback) =>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, Action callback) =>
DelayCall(delay, interval, 0, callback);
public static Timer DelayCall(TimeSpan delay, TimeSpan interval, int count, Action callback)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(TimeSpan interval, int count, Action callback) =>
DelayCall(TimeSpan.Zero, interval, count, callback);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer DelayCall(TimeSpan delay, TimeSpan interval, int count, Action callback)
{
Timer t = new DelayCallTimer(delay, interval, count, callback);
DelayCallTimer t = new DelayCallTimer(delay, interval, count, callback);
t.Start();
#if DEBUG_TIMERS
t._allowFinalization = true;
#endif
return t;
}
public static Timer DelayCall<T>(TimerStateCallback<T> callback, T state) =>
DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, state);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(Action callback) => StartTimer(TimeSpan.Zero, TimeSpan.Zero, 1, callback);
public static Timer DelayCall<T>(TimeSpan delay, TimerStateCallback<T> callback, T state) =>
DelayCall(delay, TimeSpan.Zero, 1, callback, state);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, Action callback) => StartTimer(delay, TimeSpan.Zero, 1, callback);
public static Timer DelayCall<T>(TimeSpan delay, TimeSpan interval, TimerStateCallback<T> callback, T state) =>
DelayCall(delay, interval, 0, callback, state);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback) =>
StartTimer(delay, interval, 0, callback);
public static Timer DelayCall<T>(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T> callback,
T state
)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan interval, int count, Action callback) =>
StartTimer(TimeSpan.Zero, interval, count, callback);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback)
{
Timer t = new DelayStateCallTimer<T>(delay, interval, count, callback, state);
DelayCallTimer t = DelayCallTimer.GetTimer(delay, interval, count, callback);
t._selfReturn = true;
t.Start();
return t;
#if DEBUG_TIMERS
DelayCallTimer._stackTraces[t.GetHashCode()] = new StackTrace().ToString();
#endif
}
public static Timer DelayCall<T1, T2>(TimerStateCallback<T1, T2> callback, T1 t1, T2 t2) =>
DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, t1, t2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(Action callback, out TimerExecutionToken token) =>
StartTimer(TimeSpan.Zero, TimeSpan.Zero, 1, callback, out token);
public static Timer DelayCall<T1, T2>(TimeSpan delay, TimerStateCallback<T1, T2> callback, T1 t1, T2 t2) =>
DelayCall(delay, TimeSpan.Zero, 1, callback, t1, t2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, Action callback, out TimerExecutionToken token) =>
StartTimer(delay, TimeSpan.Zero, 1, callback, out token);
public static Timer DelayCall<T1, T2>(
TimeSpan delay, TimeSpan interval, TimerStateCallback<T1, T2> callback,
T1 t1, T2 t2
) => DelayCall(delay, interval, 0, callback, t1, t2);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, TimeSpan interval, Action callback, out TimerExecutionToken token) =>
StartTimer(delay, interval, 0, callback, out token);
public static Timer DelayCall<T1, T2>(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T1, T2> callback,
T1 t1, T2 t2
)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan interval, int count, Action callback, out TimerExecutionToken token) =>
StartTimer(TimeSpan.Zero, interval, count, callback, out token);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void StartTimer(TimeSpan delay, TimeSpan interval, int count, Action callback, out TimerExecutionToken token)
{
Timer t = new DelayStateCallTimer<T1, T2>(delay, interval, count, callback, t1, t2);
DelayCallTimer t = DelayCallTimer.GetTimer(delay, interval, count, callback);
t.Start();
return t;
#if DEBUG_TIMERS
DelayCallTimer._stackTraces[t.GetHashCode()] = new StackTrace().ToString();
#endif
token = new TimerExecutionToken(t);
}
public static Timer DelayCall<T1, T2, T3>(TimerStateCallback<T1, T2, T3> callback, T1 t1, T2 t2, T3 t3) =>
DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, t1, t2, t3);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer Pause(TimeSpan ms) => new(ms);
public static Timer DelayCall<T1, T2, T3>(
TimeSpan delay, TimerStateCallback<T1, T2, T3> callback, T1 t1, T2 t2, T3 t3
) =>
DelayCall(delay, TimeSpan.Zero, 1, callback, t1, t2, t3);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayCallTimer Pause(int ms) => Pause(TimeSpan.FromMilliseconds(ms));
public static Timer DelayCall<T1, T2, T3>(
TimeSpan delay, TimeSpan interval, TimerStateCallback<T1, T2, T3> callback,
T1 t1, T2 t2, T3 t3
) => DelayCall(delay, interval, 0, callback, t1, t2, t3);
public static Timer DelayCall<T1, T2, T3>(
TimeSpan delay, TimeSpan interval, int count,
TimerStateCallback<T1, T2, T3> callback, T1 t1, T2 t2, T3 t3
)
public sealed class DelayCallTimer : Timer, INotifyCompletion
{
Timer t = new DelayStateCallTimer<T1, T2, T3>(delay, interval, count, callback, t1, t2, t3);
t.Start();
internal bool _selfReturn;
#if DEBUG_TIMERS
internal bool _allowFinalization;
#endif
private Action _continuation;
private bool _complete;
return t;
}
public static Timer DelayCall<T1, T2, T3, T4>(
TimerStateCallback<T1, T2, T3, T4> callback, T1 t1, T2 t2, T3 t3, T4 t4
) =>
DelayCall(TimeSpan.Zero, TimeSpan.Zero, 1, callback, t1, t2, t3, t4);
public static Timer DelayCall<T1, T2, T3, T4>(
TimeSpan delay, TimerStateCallback<T1, T2, T3, T4> callback,
T1 t1, T2 t2, T3 t3, T4 t4
) => DelayCall(delay, TimeSpan.Zero, 1, callback, t1, t2, t3, t4);
public static Timer DelayCall<T1, T2, T3, T4>(
TimeSpan delay, TimeSpan interval,
TimerStateCallback<T1, T2, T3, T4> callback, T1 t1, T2 t2, T3 t3, T4 t4
) =>
DelayCall(delay, interval, 0, callback, t1, t2, t3, t4);
public static Timer DelayCall<T1, T2, T3, T4>(
TimeSpan delay, TimeSpan interval, int count,
TimerStateCallback<T1, T2, T3, T4> callback, T1 t1, T2 t2, T3 t3, T4 t4
)
{
Timer t = new DelayStateCallTimer<T1, T2, T3, T4>(delay, interval, count, callback, t1, t2, t3, t4);
t.Start();
return t;
}
private class DelayCallTimer : Timer
{
public DelayCallTimer(TimeSpan delay, TimeSpan interval, int count, Action callback) : base(
internal DelayCallTimer(TimeSpan delay, TimeSpan interval, int count, Action callback) : base(
delay,
interval,
count
)
{
Callback = callback;
}
) =>
_continuation = callback;
public Action Callback { get; }
internal DelayCallTimer(TimeSpan delay) : base(delay)
{
#if DEBUG_TIMERS
t._allowFinalization = true;
#endif
Start();
}
protected override void OnTick()
{
Callback?.Invoke();
_complete = true;
_continuation?.Invoke();
}
public override string ToString() => $"DelayCallTimer[{FormatDelegate(Callback)}]";
}
private class DelayStateCallTimer<T> : Timer
{
private readonly T m_State;
public DelayStateCallTimer(TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T> callback, T state)
: base(delay, interval, count)
public override void Stop()
{
Callback = callback;
m_State = state;
base.Stop();
if (_selfReturn)
{
Return();
}
}
public TimerStateCallback<T> Callback { get; }
protected override void OnTick()
internal void Return()
{
Callback?.Invoke(m_State);
if (Running)
{
logger.Error($"Timer is returned while still running! {new StackTrace()}");
return;
}
Version++; // Increment the version so if this is called from OnTick() and another timer is started, we don't have a problem
if (_poolCount >= _poolCapacity)
{
#if DEBUG_TIMERS
logger.Warning($"DelayCallTimer pool reached maximum of {_poolSize} timers");
_allowFinalization = true;
_stackTraces.Remove(GetHashCode());
#endif
return;
}
_continuation = null;
ReturnToPool(1, this, this);
}
public override string ToString() => $"DelayStateCall[{FormatDelegate(Callback)}]";
}
private class DelayStateCallTimer<T1, T2> : Timer
{
private readonly T1 m_T1;
private readonly T2 m_T2;
public DelayStateCallTimer(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T1, T2> callback,
T1 t1, T2 t2
) : base(delay, interval, count)
public static DelayCallTimer GetTimer(TimeSpan delay, TimeSpan interval, int count, Action callback)
{
Callback = callback;
m_T1 = t1;
m_T2 = t2;
if (_poolHead != null)
{
_poolCount--;
#if DEBUG_TIMERS
logger.Information($"Pool count changed: {_poolCount} ({_poolCapacity})");
#endif
var timer = GetFromPool();
timer.Init(delay, interval, count);
timer._continuation = callback;
timer._selfReturn = false;
#if DEBUG_TIMERS
timer._allowFinalization = false;
#endif
return timer;
}
_timerPoolDepletionAmount++;
#if DEBUG_TIMERS
logger.Warning($"Timer pool depleted and timer was allocated.\n{new StackTrace()});
#endif
return new DelayCallTimer(delay, interval, count, callback);
}
public TimerStateCallback<T1, T2> Callback { get; }
public override string ToString() => $"DelayCallTimer[{FormatDelegate(_continuation)}]";
protected override void OnTick()
#if DEBUG_TIMERS
internal static Dictionary<int, string> _stackTraces = new();
~DelayCallTimer()
{
Callback?.Invoke(m_T1, m_T2);
if (!_allowFinalization)
{
logger.Warning($"Pooled timer was not returned to the pool.\n{_stackTraces[GetHashCode()]}");
}
}
#endif
public override string ToString() => $"DelayStateCall[{FormatDelegate(Callback)}]";
}
public DelayCallTimer GetAwaiter() => this;
private class DelayStateCallTimer<T1, T2, T3> : Timer
{
private readonly T1 m_T1;
private readonly T2 m_T2;
private readonly T3 m_T3;
public bool IsCompleted => _complete;
public DelayStateCallTimer(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T1, T2, T3> callback,
T1 t1, T2 t2, T3 t3
) : base(delay, interval, count)
public void OnCompleted(Action continuation) => _continuation = continuation;
public void GetResult()
{
Callback = callback;
m_T1 = t1;
m_T2 = t2;
m_T3 = t3;
}
public TimerStateCallback<T1, T2, T3> Callback { get; }
protected override void OnTick()
{
Callback?.Invoke(m_T1, m_T2, m_T3);
}
public override string ToString() => $"DelayStateCall[{FormatDelegate(Callback)}]";
}
private class DelayStateCallTimer<T1, T2, T3, T4> : Timer
{
private readonly T1 m_T1;
private readonly T2 m_T2;
private readonly T3 m_T3;
private readonly T4 m_T4;
public DelayStateCallTimer(
TimeSpan delay, TimeSpan interval, int count, TimerStateCallback<T1, T2, T3, T4> callback,
T1 t1, T2 t2, T3 t3, T4 t4
) : base(delay, interval, count)
{
Callback = callback;
m_T1 = t1;
m_T2 = t2;
m_T3 = t3;
m_T4 = t4;
}
public TimerStateCallback<T1, T2, T3, T4> Callback { get; }
protected override void OnTick()
{
Callback?.Invoke(m_T1, m_T2, m_T3, m_T4);
}
public override string ToString() => $"DelayStateCall[{FormatDelegate(Callback)}]";
}
}
}

View file

@ -1,53 +0,0 @@
/*************************************************************************
* ModernUO *
* Copyright (C) 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Timer.Pause.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Runtime.CompilerServices;
namespace Server
{
public partial class Timer
{
public class DelayTaskTimer : Timer, INotifyCompletion
{
private Action _continuation;
private bool _complete;
internal DelayTaskTimer(TimeSpan delay) : base(delay) => Start();
protected override void OnTick()
{
_complete = true;
_continuation?.Invoke();
}
public DelayTaskTimer GetAwaiter() => this;
public bool IsCompleted => _complete;
public void OnCompleted(Action continuation) => _continuation = continuation;
public void GetResult()
{
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayTaskTimer Pause(TimeSpan ms) => new(ms);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DelayTaskTimer Pause(int ms) => Pause(TimeSpan.FromMilliseconds(ms));
}
}

View file

@ -0,0 +1,128 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: Timer.Pool.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Threading;
namespace Server
{
public partial class Timer
{
private const int _timerPoolDepletionThreshold = 128; // Maximum timers allocated in a single tick before we force adjust
private static int _timerPoolDepletionAmount; // Amount the pool has been depleted by
private static int _maxPoolCapacity;
private static int _poolCapacity;
private static int _poolCount;
private static DelayCallTimer _poolHead;
public static void CheckTimerPool()
{
// Anything less than this threshold and we are ok with the number of allocations.
if (_timerPoolDepletionAmount < _timerPoolDepletionThreshold)
{
_timerPoolDepletionAmount = 0;
return;
}
var growthFactor = Math.DivRem(_timerPoolDepletionAmount, _poolCapacity, out var rem);
var amountToGrow = _poolCapacity * (growthFactor + (rem > 0 ? 1 : 0));
var amountToRefill = Math.Min(_maxPoolCapacity, amountToGrow);
var maximumHit = amountToGrow > amountToRefill ? " Maximum pool size has been reached." : "";
logger.Warning($"Timer pool depleted by {_timerPoolDepletionAmount}. Refilling with {amountToRefill}.{maximumHit}");
RefillPoolAsync(amountToRefill);
_timerPoolDepletionAmount = 0;
}
public static void ConfigureTimerPool()
{
_poolCapacity = ServerConfiguration.GetOrUpdateSetting("timer.intialPoolCapacity", 1024);
_maxPoolCapacity = ServerConfiguration.GetOrUpdateSetting("timer.maxPoolCapacity", _poolCapacity * 16);
RefillPool(_poolCapacity, out var head, out var tail);
ReturnToPool(_poolCapacity, head, tail);
}
private static void ReturnToPool(int amount, DelayCallTimer head, DelayCallTimer tail)
{
tail.Attach(_poolHead);
_poolHead = head;
_poolCount += amount;
#if DEBUG_TIMERS
logger.Information($"Pool count changed: {_poolCount} ({_poolCapacity})");
#endif
}
private static DelayCallTimer GetFromPool()
{
var timer = _poolHead;
_poolHead = _poolHead._nextTimer as DelayCallTimer;
timer.Detach();
return timer;
}
internal static void RefillPool(int amount, out DelayCallTimer head, out DelayCallTimer tail)
{
#if DEBUG_TIMERS
logger.Information($"Filling pool with {amount} timers.");
#endif
head = null;
tail = null;
for (var i = 0; i < amount; i++)
{
var timer = new DelayCallTimer(TimeSpan.Zero, TimeSpan.Zero, 0, null);
timer.Attach(head);
if (i == 0)
{
tail = timer;
}
head = timer;
}
}
internal static void RefillPoolAsync(int amountToRefill)
{
ThreadPool.UnsafeQueueUserWorkItem(
static amount =>
{
RefillPool(amount, out var head, out var tail);
// Run this on the core thread
Core.LoopContext.Post(
state =>
{
if (state == null)
{
return;
}
var (listHead, listTail) = ((DelayCallTimer, DelayCallTimer))state;
ReturnToPool(amount, listHead, listTail);
_poolCapacity = amount;
},
(head, tail)
);
},
amountToRefill,
false
);
}
}
}

View file

@ -113,20 +113,25 @@ namespace Server
// This can be done in OnTick by checking if Index < Count - 1 (still more iterations left)
RemoveTimer(timer);
if (finished)
{
timer.InternalStop();
}
var version = timer.Version;
prof?.Start();
timer.OnTick();
prof?.Finish();
if (timer.Running && !finished)
// If the timer has not been stopped, and it has not been altered (shared timers)
if (timer.Running && timer.Version == version)
{
timer.Delay = timer.Interval;
timer.Next = Core.Now + timer.Interval;
AddTimer(timer, (long)timer.Delay.TotalMilliseconds);
if (finished)
{
timer.Stop();
}
else
{
timer.Delay = timer.Interval;
timer.Next = Core.Now + timer.Interval;
AddTimer(timer, (long)timer.Delay.TotalMilliseconds);
}
}
timer = next;
@ -200,8 +205,8 @@ namespace Server
{
var now = DateTime.UtcNow;
tw.WriteLine("Date: {0}", now);
tw.WriteLine();
tw.WriteLine("Date: {0}\n", now);
tw.WriteLine("Pool - Count: {0}; Size {1}\n", _poolCount - _timerPoolDepletionAmount, _poolCapacity);
var total = 0.0;
var hash = new Dictionary<string, int>();
@ -221,9 +226,11 @@ namespace Server
}
}
tw.WriteLine("Timers:");
foreach (var (name, count) in hash.OrderByDescending(o => o.Value))
{
tw.WriteLine($"Type: {name}; Count: {count}; Percent: {count / total}%");
tw.WriteLine($"- Type: {name}; Count: {count}; Percent: {count / total}%");
}
tw.WriteLine();

View file

@ -21,12 +21,16 @@ namespace Server
{
public partial class Timer
{
private static readonly ILogger logger = LogFactory.GetLogger(typeof(Timer));
protected internal static readonly ILogger logger = LogFactory.GetLogger(typeof(Timer));
public static void Configure()
{
ConfigureTimerPool();
}
// We need to know what ring/slot we are in so we can be removed if we are "head" of the link list.
private int _ring;
private int _slot;
private long _remaining;
private Timer _nextTimer;
private Timer _prevTimer;
@ -37,10 +41,11 @@ namespace Server
public Timer(TimeSpan delay, TimeSpan interval, int count = 0) => Init(delay, interval, count);
public void Init(TimeSpan delay, TimeSpan interval, int count)
protected void Init(TimeSpan delay, TimeSpan interval, int count)
{
Running = false;
Delay = delay;
Index = 0;
Interval = interval;
Count = count;
_nextTimer = null;
@ -55,6 +60,8 @@ namespace Server
}
}
protected int Version { get; set; } // Used to determine if a timer was altered and we should abandon it.
public DateTime Next { get; private set; }
public TimeSpan Delay { get; set; }
public TimeSpan Interval { get; set; }
@ -87,21 +94,14 @@ namespace Server
return this;
}
public Timer Stop()
public virtual void Stop()
{
if (!Running)
{
return this;
return;
}
RemoveTimer(this);
InternalStop();
return this;
}
private void InternalStop()
{
Running = false;
var prof = GetProfile();

View file

@ -0,0 +1,60 @@
/*************************************************************************
* ModernUO *
* Copyright 2019-2021 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: TimerExecutionToken.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Runtime.CompilerServices;
namespace Server
{
public struct TimerExecutionToken
{
private Timer.DelayCallTimer _timer;
internal TimerExecutionToken(Timer.DelayCallTimer timer) => _timer = timer;
public bool Running
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _timer?.Running == true;
}
public int Index
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _timer?.Index ?? 0;
}
public int RemainingCount
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _timer?.RemainingCount ?? 0;
}
public DateTime Next
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _timer?.Next ?? DateTime.MinValue;
}
public void Cancel()
{
_timer?.Stop();
_timer?.Return();
_timer = null;
this = default;
}
}
}

View file

@ -419,7 +419,7 @@ namespace Server
m_DiskWriteHandle.Set();
Timer.DelayCall(FinishWorldSave);
Timer.StartTimer(FinishWorldSave);
}
private static void ProcessDecay()