It might be not a good idea indeed, because if someone else uses the same object reference to do a lock
, you could have a deadlock. If there is a chance your locked object is accessible outside your own code, then someone else could break your code.
Imagine the following example based on your code:
namespace ClassLibrary1
{
public class Foo : IProduct
{
}
public interface IProduct
{
}
public class MyClass
{
public List<IProduct> myOriginalProductList = new List<IProduct> { new Foo(), new Foo() };
public void Test(Action<IEnumerable<IProduct>> handler)
{
List<IProduct> otherProductList = new List<IProduct> { new Foo(), new Foo() };
Parallel.ForEach(myOriginalProductList, product =>
{
lock (otherProductList)
{
if (handler != null)
{
handler(otherProductList);
}
otherProductList.Add(product);
}
});
}
}
}
Now you compile your library, send it to a customer, and this customer writes in his code:
public class Program
{
private static void Main(string[] args)
{
new MyClass().Test(z => SomeMethod(z));
}
private static void SomeMethod(IEnumerable<IProduct> myReference)
{
Parallel.ForEach(myReference, item =>
{
lock (myReference)
{
// Some stuff here
}
});
}
}
Then there could be a nice hard-to-debug deadlock for your customer, each of two used thread waiting for the otherProductList
instance to be not locked anymore.
I agree, this scenario is unlikely to happen, but it illustrates that if your locked reference is visible in a piece of code you do not own, by any possible way, then there's a possibility for the final code to be broken.