I have dictionary:
private static Dictionary<string, List<Event>> eventsForArea;
initialize it in static constructor.
And I have method (I only insert part of the method where I have references to dictionary, but I think it is enough to understand my question.):
public void Analyze()
{
if (!eventsForArea.ContainsKey(Area.Name))
{
lock (eventsForArea)
eventsForArea.Add(Area.Name, allUnfinished);
var unknownUnfinished = ..;
foreach (var @event in unknownUnfinished)
{
eventsForArea[Area.Name].Remove(@event);
}
}
else
{
unfinished = eventsForArea[Area.Name].ToArray();
}
foreach (var @event in Events)
{
try
{
var unfinishedEventsForAsixId = ..;
if (!@event.CheckIfPresent(registers))
{
foreach (var unfinishedEvent in unfinishedEventsForAsixId)
{
eventsForArea[Area.Name].Remove(unfinishedEvent);
}
}
else
{
eventsForArea[Area.Name].Add(eventWithId);
}
}
catch (Exception e)
{
}
}
}
The startup method is asynchronous, it may be run multiple times at the same time. Without lock (eventsForArea)
it throw exception:
"Object reference not set to an instance of an object"
Now work, but I dont sure is it enough that there is a lock only in this place?