diff --git a/src/AngleSharp.Js.Tests/ConstructorTests.cs b/src/AngleSharp.Js.Tests/ConstructorTests.cs index 0ec11ca..3e58693 100644 --- a/src/AngleSharp.Js.Tests/ConstructorTests.cs +++ b/src/AngleSharp.Js.Tests/ConstructorTests.cs @@ -1,3 +1,6 @@ +using System.Linq; +using AngleSharp.Dom; + namespace AngleSharp.Js.Tests { using NUnit.Framework; @@ -35,5 +38,24 @@ public async Task CustomEventConstructedWithBubblesTrue() var result = document.QuerySelector("#result").TextContent; Assert.AreEqual("true", result); } + + [Test] + public void CustomEventConstructedConcurrently() + { + var ctx1 = BrowsingContext.New(Configuration.Default.WithJs()); + var ctx2 = BrowsingContext.New(Configuration.Default.WithJs()); + var html = "
"; + Parallel.Invoke(() => Assert(ctx1), () => Assert(ctx2)); + return; + + void Assert(IBrowsingContext context) => Task + .Run(async () => + { + var document = await context.OpenAsync(m => m.Content(html)); + var result = document.QuerySelector("#result").TextContent; + NUnit.Framework.Assert.AreEqual("foo", result); + }) + .Wait(); + } } } diff --git a/src/AngleSharp.Js/Cache/CreatorCache.cs b/src/AngleSharp.Js/Cache/CreatorCache.cs index 5003d93..3c1188e 100644 --- a/src/AngleSharp.Js/Cache/CreatorCache.cs +++ b/src/AngleSharp.Js/Cache/CreatorCache.cs @@ -4,7 +4,7 @@ using Jint.Native.Object; using Jint.Runtime.Descriptors; using System; -using System.Collections.Generic; +using System.Collections.Concurrent; using System.Linq; using System.Reflection; @@ -12,7 +12,7 @@ namespace AngleSharp.Js.Cache { static class CreatorCache { - private static readonly Dictionary> _constructorActions = new Dictionary>(); + private static readonly ConcurrentDictionary> _constructorActions = new(); public static Action GetConstructorAction(this Type type) { @@ -36,13 +36,13 @@ public static Action GetConstructorAction(this T action = (e, o) => { }; } - _constructorActions.Add(type, action); + _constructorActions.TryAdd(type, action); } return action; } - private static readonly Dictionary> _constructorFunctionActions = new Dictionary>(); + private static readonly ConcurrentDictionary> _constructorFunctionActions = new(); public static Action GetConstructorFunctionAction(this Type type) { @@ -69,13 +69,13 @@ public static Action GetConstructorFunctionActio action = (e, o) => { }; } - _constructorFunctionActions.Add(type, action); + _constructorFunctionActions.TryAdd(type, action); } return action; } - private static readonly Dictionary> _instanceActions = new Dictionary>(); + private static readonly ConcurrentDictionary> _instanceActions = new(); public static Action GetInstanceAction(this Type type) { @@ -105,7 +105,7 @@ public static Action GetInstanceAction(this Type action = (e, o) => { }; } - _instanceActions.Add(type, action); + _instanceActions.TryAdd(type, action); } return action;