41 lines
1.9 KiB
C#

using System.Diagnostics;
namespace PlotDirector.Companion.Client;
// Pumped by a Windows Forms timer on Word's original UI thread. Actions never
// execute on producers/Task.Run. Each action must itself bound its COM access.
public sealed class WordAccessScheduler
{
private readonly Dictionary<string, Action> work = new();
private Queue<string> order = new();
private readonly int ownerThread = Environment.CurrentManagedThreadId;
private DateTime quietUntil;
public const int Capacity = 64;
public int Depth => work.Count;
public long Superseded { get; private set; }
public event Action<string, double>? Measured;
public event Action<Exception>? Failed;
private void AssertOwner() { if (Environment.CurrentManagedThreadId != ownerThread) throw new InvalidOperationException("Word work must stay on its owning UI thread."); }
public bool Post(string key, Action action)
{
AssertOwner();
if (work.ContainsKey(key)) Superseded++;
else { if (work.Count >= Capacity) return false; order.Enqueue(key); }
work[key] = action; return true;
}
public void Cancel(string key) { AssertOwner(); work.Remove(key); order = new Queue<string>(order.Where(k => k != key)); }
public void Clear() { AssertOwner(); work.Clear(); order.Clear(); }
public void PrioritizeAuthor(TimeSpan quietPeriod) { AssertOwner(); quietUntil = DateTime.UtcNow + quietPeriod; }
public bool Pump()
{
AssertOwner();
if (DateTime.UtcNow < quietUntil || work.Count == 0) return false;
var key = work.ContainsKey("selection") ? "selection" : order.Peek();
var action = work[key]; Cancel(key);
var watch = Stopwatch.StartNew();
try { action(); } catch (Exception ex) { Failed?.Invoke(ex); }
finally { Measured?.Invoke(key.Split(':')[0], watch.Elapsed.TotalMilliseconds); }
return true;
}
}