Skip to content

Commit 5fc2a00

Browse files
ooplesclaude
andcommitted
fix: add thread safety to agentglobalconfiguration for concurrent access
Added lock-based synchronization to protect the shared _apiKeys dictionary from concurrent access issues. Changes: - Added private static lock object for synchronization - Protected SetApiKey method with lock to prevent race conditions - Changed ApiKeys property to return a snapshot copy under lock instead of exposing mutable dictionary This prevents race conditions when multiple threads configure or read API keys concurrently, which could occur in multi-threaded applications or during parallel model building operations. Fixes PR #423 comment #1. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
1 parent 5e6bc69 commit 5fc2a00

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/Agents/AgentGlobalConfiguration.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ namespace AiDotNet.Agents;
5151
public static class AgentGlobalConfiguration
5252
{
5353
private static readonly Dictionary<LLMProvider, string> _apiKeys = new();
54+
private static readonly object _lock = new object();
5455

5556
/// <summary>
5657
/// Gets a read-only dictionary of configured API keys indexed by LLM provider.
@@ -85,7 +86,16 @@ public static class AgentGlobalConfiguration
8586
/// Never commit code that logs or exposes these values in production.
8687
/// </para>
8788
/// </remarks>
88-
public static IReadOnlyDictionary<LLMProvider, string> ApiKeys => _apiKeys;
89+
public static IReadOnlyDictionary<LLMProvider, string> ApiKeys
90+
{
91+
get
92+
{
93+
lock (_lock)
94+
{
95+
return new Dictionary<LLMProvider, string>(_apiKeys);
96+
}
97+
}
98+
}
8999

90100
/// <summary>
91101
/// Gets or sets the default LLM provider to use when one is not explicitly specified.
@@ -205,9 +215,13 @@ public static void Configure(Action<AgentGlobalConfigurationBuilder> configure)
205215
/// <remarks>
206216
/// This internal method is called by the AgentGlobalConfigurationBuilder to store configured API keys.
207217
/// It is not intended for direct use - use the Configure() method with the fluent builder instead.
218+
/// Thread-safe for concurrent access.
208219
/// </remarks>
209220
internal static void SetApiKey(LLMProvider provider, string apiKey)
210221
{
211-
_apiKeys[provider] = apiKey;
222+
lock (_lock)
223+
{
224+
_apiKeys[provider] = apiKey;
225+
}
212226
}
213227
}

0 commit comments

Comments
 (0)