I have a function which deserialize an Xml document and create objects from it.
I want the objects to be stored into cache so i don’t have to deserialize the xml every time i need to get data from it.
public class XMLDeserializer
{
public event OnElementDeserialized OnElementDeserializedCallback;
public void DeserializeXml(string xmlPath)
{
// implementation
}
}
public class XMLDeserializerFacade
{
private static object _lockObject = new object();
private XMLDeserializer xmlDeserializer;
private ICacheProvider cacheProvider;
public XMLDeserializerFacade(XMLDeserializer xmlDeserializer, ICacheProvider cacheProvider)
{
this.xmlDeserializer = xmlDeserializer;
this.cacheProvider = cacheProvider;
xmlDeserializer.OnElementDeserializedCallback += delegate(object element)
{
cacheProvider.Add("uniqueKey", element);
// is here in lock as well or i have to lock it again?
};
}
public void DeserializeXml(string xmlPath)
{
lock(_lockObject)
{
xmlDeserializer.DeserializeXml(xmlPath);
// From here it will go to
// cacheProvider.Add("uniqueKey", element); callback
}
}
}
When i want to deserialize the xml, i call
XMLDeserializerFacade.DeserializeXml("file.xml")
My question is that i should use lock also inside the OnElementDeserializedCallback callback as well?
Thank you
It depends a lot on the specific implementation. If the code that invokes that is on the same thread as the main
lock/DeserializeXml, and it uses the synchronous version (OnElementDeserializedCallback(...)orOnElementDeserializedCallback.Invoke(...)) – then it will already be inside the existing lock, because the lock is essentially tied to the thread.If the implementation uses an asynchronous implementation (
BeginInvoke,Task,ThreadPooletc), then no: it will not be inside the lock.If unsure, you could lock in both places (since locks are re-entrant, it doesn’t matter if you end up having nested locking twice from the same thread); however, if it turns out it is asynchronous, but it also then tries to join back to the callback (
Delegate.EndInvoke,Task.Wait, etc) then it could totally deadlock.