Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions dotnet/src/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,13 @@ namespace GitHub.Copilot.SDK;
/// </example>
public partial class CopilotSession : IAsyncDisposable
{
private readonly HashSet<SessionEventHandler> _eventHandlers = new();
/// <summary>
/// Multicast delegate used as a thread-safe, insertion-ordered handler list.
/// The compiler-generated add/remove accessors use a lock-free CAS loop over the backing field.
/// Dispatch reads the field once (inherent snapshot, no allocation).
/// Expected handler count is small (typically 1–3), so Delegate.Combine/Remove cost is negligible.
/// </summary>
private event SessionEventHandler? _eventHandlers;
private readonly Dictionary<string, AIFunction> _toolHandlers = new();
private readonly JsonRpc _rpc;
private volatile PermissionRequestHandler? _permissionHandler;
Expand Down Expand Up @@ -243,8 +249,8 @@ void Handler(SessionEvent evt)
/// </example>
public IDisposable On(SessionEventHandler handler)
{
_eventHandlers.Add(handler);
return new ActionDisposable(() => _eventHandlers.Remove(handler));
_eventHandlers += handler;
return new ActionDisposable(() => _eventHandlers -= handler);
}

/// <summary>
Expand All @@ -256,11 +262,8 @@ public IDisposable On(SessionEventHandler handler)
/// </remarks>
internal void DispatchEvent(SessionEvent sessionEvent)
{
foreach (var handler in _eventHandlers.ToArray())
{
// We allow handler exceptions to propagate so they are not lost
handler(sessionEvent);
}
// Reading the field once gives us a snapshot; delegates are immutable.
_eventHandlers?.Invoke(sessionEvent);
}

/// <summary>
Expand Down Expand Up @@ -550,7 +553,7 @@ await InvokeRpcAsync<object>(
// Connection is broken or closed
}

_eventHandlers.Clear();
_eventHandlers = null;
_toolHandlers.Clear();

_permissionHandler = null;
Expand Down
Loading