Skip to content

Commit

Permalink
Optimize event dispatching (#949)
Browse files Browse the repository at this point in the history
This PR reduces the amount of event dispatches being enqueued onto the STA thread. Previously, it was possible to have the STA thread execute >80 callbacks queued and for them all to execute within 300ms.

This is related to #941.
  • Loading branch information
dalyIsaac committed Jul 7, 2024
1 parent 40d0486 commit b50e7c3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
27 changes: 27 additions & 0 deletions src/Whim/Store/RootSector/MutableRootSector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ namespace Whim;

internal class MutableRootSector : SectorBase, IDisposable
{
private readonly IContext _ctx;
private readonly object _lock = new();
private bool _disposedValue;
private bool _dispatchEventsScheduled;

public MonitorSector MonitorSector { get; }
public WindowSector WindowSector { get; }
Expand All @@ -18,6 +21,7 @@ internal class MutableRootSector : SectorBase, IDisposable

public MutableRootSector(IContext ctx, IInternalContext internalCtx)
{
_ctx = ctx;
MonitorSector = new MonitorSector(ctx, internalCtx);
WindowSector = new WindowSector(ctx, internalCtx);
WorkspaceSector = new WorkspaceSector(ctx, internalCtx);
Expand All @@ -35,6 +39,29 @@ public override void Initialize()

public override void DispatchEvents()
{
lock (_lock)
{
if (_dispatchEventsScheduled)
{
Logger.Debug("Dispatch events already scheduled");
return;
}

if (HasQueuedEvents)
{
Logger.Debug("Queued events detected, scheduling dispatch");
_dispatchEventsScheduled = true;
_ctx.NativeManager.TryEnqueue(DispatchEventsFn);
}
}
}

private void DispatchEventsFn()
{
// We can't lock here because of the STA, so we set the flag to false before we start
// dispatching events.
_dispatchEventsScheduled = false;

Logger.Debug("Dispatching events");
MonitorSector.DispatchEvents();
WindowSector.DispatchEvents();
Expand Down
11 changes: 2 additions & 9 deletions src/Whim/Store/Store.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,9 @@ public Result<TResult> Dispatch<TResult>(Transform<TResult> transform)
}
finally
{
bool hasQueuedEvents = _root.MutableRootSector.HasQueuedEvents;
_lock.ExitWriteLock();
_root.DoLayout();
if (hasQueuedEvents)
{
Logger.Debug("Enqueuing dispatch events");
_ctx.NativeManager.TryEnqueue(_root.DispatchEvents);
}
_root.DispatchEvents();
_lock.ExitWriteLock();
}
}).Result;
}
Expand Down

0 comments on commit b50e7c3

Please sign in to comment.