是否应该重构此 C# 代码以使用 Lazy?类代替?
我有以下代码,可以在同一秒通过多个网络请求调用。因此,我不希望第二个以上请求访问数据库,而是等到第一个请求访问数据库。
我应该重构它以使用 Lazy
keyword 类吗?如果同时发生 10 次对 Lazy
代码段的调用,那么其中 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
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Lazy
是的,您可以使用MSDN 一个>:
是的,它不是一个关键字 - 它是一个 .NET 框架类,它形式化了延迟初始化经常需要的用例,并提供开箱即用的功能,因此您不必“手动”执行此操作。
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".
正如@BrokenGlass 指出的那样,它是安全的。但我无法抗拒,不得不进行测试...
只打印了一个线程ID...
但是,哪个更快?从我得到的结果来看...
执行代码 100 次
执行代码 100000000 次
测试代码:
测试方法:
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: