If have a snippet of code that i found back in an old project of mine. I just can’t figure out why i had this one included.
public void AddParking(Parking parking)
{
if (allParkings == null)
{
allParkings = new ObservableCollection<Parking>();
}
allParkings.Add(parking);
if (ParkingAddedEvent != null)
{
ParkingAddedEvent(this, new ParkingAddedEventArgs(parking));
}
}
This one’s in my ParkingRepository class, which is in the model folder. I’m using mvvm light toolkit. I’m just wondering what functionality this has in the app.
To make clear, i’m talking about the second if-statement, with the ParkingAddedEvent.
You first check if there are any event listeners for the ParkingAddedEvent and if there are, you will raise the event. The effect of this event depends on the listeners.
The implementation that you have here is not thread-safe. The following should be thread-safe alternative:
I use
Thread.MemoryBarrier()to prevent compiler optimization that could eliminate the local variable. If that would happen, the code would be identical with your current implementation.There is also another thread-safety issue with the collection initializer, but that is only a problem if
AddParking()method is called from different threads.