From bd45c4dac02c701f9ff213e26840db141f5076e4 Mon Sep 17 00:00:00 2001 From: Washi Date: Fri, 14 Oct 2022 19:00:58 +0200 Subject: [PATCH] Guard lazylist modification methods with locks. --- src/AsmResolver/Collections/LazyList.cs | 53 +++++++++++++++++-------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/src/AsmResolver/Collections/LazyList.cs b/src/AsmResolver/Collections/LazyList.cs index 139761acf..6a88b6193 100644 --- a/src/AsmResolver/Collections/LazyList.cs +++ b/src/AsmResolver/Collections/LazyList.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Threading; namespace AsmResolver.Collections { @@ -12,6 +13,7 @@ namespace AsmResolver.Collections [DebuggerDisplay("Count = {" + nameof(Count) + "}")] public abstract class LazyList : IList { + private readonly ReaderWriterLockSlim _lock = new(LockRecursionPolicy.NoRecursion); private readonly List _items; /// @@ -41,8 +43,11 @@ public TItem this[int index] } set { - EnsureIsInitialized(); - OnSetItem(index, value); + lock (_items) + { + EnsureIsInitialized(); + OnSetItem(index, value); + } } } @@ -104,7 +109,7 @@ private void EnsureIsInitialized() { if (!IsInitialized) { - lock (this) + lock (_items) { if (!IsInitialized) { @@ -128,8 +133,11 @@ private void EnsureIsInitialized() /// public void Clear() { - OnClearItems(); - IsInitialized = true; + lock (_items) + { + OnClearItems(); + IsInitialized = true; + } } /// @@ -149,11 +157,15 @@ public void CopyTo(TItem[] array, int arrayIndex) /// public bool Remove(TItem item) { - EnsureIsInitialized(); - int index = Items.IndexOf(item); - if (index == -1) - return false; - OnRemoveItem(index); + lock (_items) + { + EnsureIsInitialized(); + int index = Items.IndexOf(item); + if (index == -1) + return false; + OnRemoveItem(index); + } + return true; } @@ -167,8 +179,11 @@ public int IndexOf(TItem item) /// public void Insert(int index, TItem item) { - EnsureIsInitialized(); - OnInsertItem(index, item); + lock (_items) + { + EnsureIsInitialized(); + OnInsertItem(index, item); + } } /// @@ -178,15 +193,21 @@ public void Insert(int index, TItem item) /// The items to insert. private void InsertRange(int index, IEnumerable items) { - EnsureIsInitialized(); - OnInsertRange(index, items); + lock (_items) + { + EnsureIsInitialized(); + OnInsertRange(index, items); + } } /// public void RemoveAt(int index) { - EnsureIsInitialized(); - OnRemoveItem(index); + lock (_items) + { + EnsureIsInitialized(); + OnRemoveItem(index); + } } ///