diff --git a/lib/PuppeteerSharp/Browser.cs b/lib/PuppeteerSharp/Browser.cs index 5cf188910..0bdd54bb3 100644 --- a/lib/PuppeteerSharp/Browser.cs +++ b/lib/PuppeteerSharp/Browser.cs @@ -56,10 +56,9 @@ internal Browser( TargetsMap = new ConcurrentDictionary(); ScreenshotTaskQueue = new TaskQueue(); DefaultContext = new BrowserContext(Connection, this, null); - _contexts = contextIds.ToDictionary( + _contexts = new ConcurrentDictionary(contextIds.ToDictionary( contextId => contextId, - contextId => new BrowserContext(Connection, this, contextId)); - + contextId => new BrowserContext(Connection, this, contextId))); Connection.Disconnected += Connection_Disconnected; Connection.MessageReceived += Connect_MessageReceived; @@ -72,7 +71,7 @@ internal Browser( internal IDictionary TargetsMap { get; } - private readonly Dictionary _contexts; + private readonly ConcurrentDictionary _contexts; private readonly ILogger _logger; private readonly Func _targetFilterCallback; private Task _closeTask; @@ -212,7 +211,7 @@ public async Task CreateIncognitoBrowserContextAsync() { var response = await Connection.SendAsync("Target.createBrowserContext", null).ConfigureAwait(false); var context = new BrowserContext(Connection, this, response.BrowserContextId); - _contexts[response.BrowserContextId] = context; + _contexts.TryAdd(response.BrowserContextId, context); return context; } @@ -403,7 +402,7 @@ internal async Task DisposeContextAsync(string contextId) { BrowserContextId = contextId }).ConfigureAwait(false); - _contexts.Remove(contextId); + _contexts.TryRemove(contextId, out var _); } private async void Connection_Disconnected(object sender, EventArgs e)