I keep finding myself surprised at what C# can do with the new C# 3.0 features. I was going to throw something out there that I thought would be so-so, but it turns out to be better than I hoped for. Here 'tis.
Make an object to hold all the values (let's just call it a "value holder" ... not to be confused with any other usage of that term though). It has nothing but C# automatic properties. Then make another object which gives access to the value holder. Call the second object the "SynchronicityHandler" (sucky term, but will get the concept across).
Let the SynchronicityHandler do the locking. It can now be generic. So here's what you get:
public class PersonValueHolder
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool HasCollegeDegree { get; set; }
}
public class SyncronicityHandler<T>
{
private object locker = new object();
private T valueHolder;
public SynchronicityHandler(T theValueHolder)
{
this.valueHolder = theValueHolder;
}
public void WorkWithValueHolderSafely(Action<T> yourAction)
{
lock(locker)
{
yourAction(valueHolder);
}
}
}
Here's an example of how you'd call it:
var myPerson = new SynchronicityHandler(new PersonValueHolder());
// Safely setting values
myPerson.WorkWithValueHolderSafely( p =>
{
p.FirstName = "Douglas";
p.LastName = "Adams";
p.HasCollegeDegree = true;
});
// Safely getting values (this syntax could be improved with a little effort)
string theFirstName = null;
myPerson.WorkWithValueHolderSafely( p=> theFirstName = p.FirstName);
Console.Writeline("Name is: " + theFirstName); // Outputs "Name is: Douglass".
Really, now that I think about it, the "value holder" doesn't have to be just automatic properties. It can be any object.