我有以下代码,可以同时通过多个网络请求调用。因此,我不希望第二个+请求命中数据库,而是等到第一个请求。
我应该重构它以使用Lazy<T>
关键字类吗?如果Lazy<T>
同时发生对一段代码的 10 次调用,那么其中 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
}