using System; using System.Runtime.CompilerServices; namespace Cysharp.Threading.Tasks.Internal { internal sealed class PooledDelegate : ITaskPoolNode> { static TaskPool> pool; PooledDelegate nextNode; public ref PooledDelegate NextNode => ref nextNode; static PooledDelegate() { TaskPool.RegisterSizeGetter(typeof(PooledDelegate), () => pool.Size); } readonly Action runDelegate; Action continuation; PooledDelegate() { runDelegate = Run; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Action Create(Action continuation) { if (!pool.TryPop(out var item)) { item = new PooledDelegate(); } item.continuation = continuation; return item.runDelegate; } [MethodImpl(MethodImplOptions.AggressiveInlining)] void Run(T _) { var call = continuation; continuation = null; if (call != null) { pool.TryPush(this); call.Invoke(); } } } }