Recently I had to lock collections (of type List<T>
) when items were added or removed. Because several collections were used in given code instead of creating helper methods for each collection, I made an extension methods:
public static class MyExtension
{
public static void AddThreadSafely<T>(this ICollection<T> collection, T item)
{
if (collection == null)
throw new ArgumentNullException("collection");
bool locked = false;
try
{
System.Threading.Monitor.Enter(collection, ref locked);
collection.Add(item);
}
finally
{
if (locked)
System.Threading.Monitor.Exit(collection);
}
}
//The same with remove
}
and then simply replaced Add
with AddThreadSafely
.
I like the simplicity of this solution but... What are the drawbacks of using this method? Will it be good idea to use this method of locking collections in future projects?