I need to lock a couple of variables in my event handler so that separate threads cannot access them at the same time. After researching SO, I learned that I should lock on a static private object and wrap my code around that lock. But my question is related to how much code can be put inside the lock. Below is my event handler code, but I am inclined to wrap the entire code inside the lock statement, but something tells me there is too much code being wrapped.
Are there guidelines to this? As you can see, the code updates an important variable (currentNumberOfHighSeverityAlarms). This must be managed by one thread at a time. It is at the beginning of the code and at the end. Is it ok to wrap the entire try/catch into a lock statement? I'm just not sure where to put the lock statement exactly.
private void AlarmList_WindowDataChanged(object sender, AlsWindowDataChangeEventArgs e)
{
try
{
if (e.WindowDataItems != null && e.TotalSize > 0)
{
var previousNumberOfHighSeverityAlarms = currentNumberOfHighSeverityAlarms;
currentNumberOfHighSeverityAlarms = e.WindowDataItems.Count(
al => Convert.ToInt32(al.Fields[8]) >= m_highSeverityRangeMinimum
&& Convert.ToInt32(al.Fields[8]) <= m_highSeverityRangeMaximum);
m_alarmManagementService.HighPriorityUnacknowledgedAlarmsExist = currentNumberOfHighSeverityAlarms > 0;
if (currentNumberOfHighSeverityAlarms > previousNumberOfHighSeverityAlarms)
{
SoundManagerComponent.AlarmsMuted = false;
if (previousNumberOfHighSeverityAlarms == 0 && m_alarmListStartupCompleted == false)
{
var highSeveritySoundFile = SystemConfigurationComponent.GetSubsystemSetting("gcs", "alarmmanagementservice", "HighSeveritySoundFile").SettingValue;
SoundManagerComponent.SetRepeatSound(highSeveritySoundFile, TimeSpan.FromSeconds(3), SoundManagerComponent.AlarmsVolume);
m_alarmListStartupCompleted = true;
LoggingComponent.WriteApplicationLog("Alarm sound turned on. New high-severity alarms generated.", "Main Toolbar AlarmViewer");
}
}
var highSeverityAlarmsExistInAlarmViewer = e.WindowDataItems.Any(
al => Convert.ToInt32(al.Fields[8]) >= m_highSeverityRangeMinimum
&& Convert.ToInt32(al.Fields[8]) <= m_highSeverityRangeMaximum);
if (!highSeverityAlarmsExistInAlarmViewer)
{
SoundManagerComponent.StopRepeatedSound();
}
}
else
{
SoundManagerComponent.StopRepeatedSound();
m_alarmManagementService.HighPriorityUnacknowledgedAlarmsExist = false;
currentNumberOfHighSeverityAlarms = 0;
LoggingComponent.WriteApplicationLog("Alarm sound turned off. No high-severity alarms exist.", "Main Toolbar AlarmViewer");
}
}
catch (Exception ex)
{
Trace.TraceError("Error while counting the number of high-severity alarms. Ex: " + ex.Message);
}
}