The function GetYYY()
is called from an ASP.NET base page. So it can happen at the same time for several users. _data
is something which should be initialized only once. However, the lock does not lock the static list. From our log, the log.Debug
is executed twice and 2 values are logged (see the comment below). Why does the lock not work?
public class XXX
{
private static List<YYY> _data = new List<YYY>();
public List<YYY> GetYYY()
{
lock (_data)
{
if (_data.Count > 0)
{
return _data;
}
_data = new List<YYY>();
try
{
var query = @" SELECT ...";
using (var dab = GetDataAccessBlock())
{
OracleDataReader reader = dab.ExecuteSQLAsReader(query);
while (reader.Read())
{
_data.Add(new YYY
{
P1 = reader["P1"].ToString(),
P2 = ...
});
}
log.Debug(_data.Count + " values are returned. this should be called only once when app restarts"); //this logs twice with wrong numbers 863 and 787... when there is only one user, it should be 432
}
}
catch (Exception ex)
{
log.Error("..." );
}
return _data;
}
}
}
2