You might want to read SyncLock and SyncRoot, which are used to create a common lock pattern for your objects. Since you do not want to lock the enitre object, you often have a SyncRoot that you lock.
An example of this is an ArrayList or ICollection, which have SyncRoot, which you should use to lock the collection. You can learn more about Stream Sync on MSDN .
But overall, this is exactly the same as Mark pointed out, be careful, check, check, check and do one more test!
SyncLock Example
public class Person { public decimal Salary { get;set; } public string Name { get; set; } public readonly object SyncRoot = new object(); }
Then you can approach the lock as follows:
var person = new Person { Name = "Bill", Salary = 1000000 }; lock(person.SyncRoot) { IncreasSalary(); }
A bad pattern should do lock(this) NEVER do it!
There is also somthing called Double Checking Lock , which is not related to .NET, you can also read this article on "Strategic locking, threaded interface and locking with binding" .
Thread Safety Testing
If you want to check thread safety, I recommend that you check Unit test for thread safety , the accepted answer points to Microsoft Chess , which will help you determine deadlocks in your application.
Filip Ekberg
source share