I have the following code which could be called via multiple web-requests at the same second. As such, I don't want the second+ request hitting the database, but waiting until the first one does.
Should I refactor this to use the Lazy<T>
keyword class instead? If 10 calls to a Lazy<T>
piece of code occur at the same time, do 9 of those calls wait for the first one to complete?
public class ThemeService : IThemeService
{
private static readonly object SyncLock = new object();
private static IList<Theme> _themes;
private readonly IRepository<Theme> _themeRepository;
<snip snip snip>
#region Implementation of IThemeService
public IList<Theme> Find()
{
if (_themes == null)
{
lock (SyncLock)
{
if (_themes == null)
{
// Load all the themes from the Db.
_themes = _themeRepository.Find().ToList();
}
}
}
return _themes;
}
<sip snip snip>
#endregion
}
Yes you can use
Lazy<T>
From MSDN:
And yes, it's not a keyword - its a .NET framework class that formalizes the often required use case for lazy initialization and offers this out of the box so you don't have to do it "manually".
As @BrokenGlass pointed out it is safe. But I couldn't resist and had to make a test...
Only one thread id is printed...
But, which one is faster? From the results I got...
Executing the code 100 times
Executing the code 100000000 times
Test code:
Test method: