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

@ -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)}]";
}
}
}