我有如下代码,可能会被多个Web请求同时调用。因此,我不希望第二个及之后的请求击中数据库,而是等待第一个请求完成后再处理。
是否应该重构这段代码,使用
是否应该重构这段代码,使用
Lazy<T>
类?如果同时发生10次对Lazy<T>
代码块的调用,那么其中9个调用是否会等待第一个调用完成后再执行?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
}