是否应将此C#代码重构为使用Lazy< T>.课吗?

编程入门 行业动态 更新时间:2024-10-11 19:19:34
本文介绍了是否应将此C#代码重构为使用Lazy< T>.课吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码,可以在同一秒通过多个Web请求来调用.因此,我不希望第二个以上的请求到达数据库,而是等到第一个以上的请求到达数据库.

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.

我应该将其重构为使用Lazy<T> 关键字类吗?如果同时发生10个对Lazy<T>代码的调用,那么这些调用中有9个等待第一个调用完成吗?

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 }

推荐答案

是的,您可以使用Lazy<T>

来自 MSDN :

默认情况下,惰性对象是线程安全的.也就是说,如果 构造函数没有指定线程安全的种类,Lazy 它创建的对象是线程安全的.在多线程方案中, 第一个访问线程安全的Lazy的Value属性的线程 对象针对所有线程上的所有后续访问将其初始化,然后 所有线程共享相同的数据.因此,这无关紧要 线程会初始化对象,并且竞争条件是良性的.

By default, Lazy objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the Lazy objects it creates are thread-safe. In multithreaded scenarios, the first thread to access the Value property of a thread-safe Lazy object initializes it for all subsequent accesses on all threads, and all threads share the same data. Therefore, it does not matter which thread initializes the object, and race conditions are benign.

是的,它不是关键字-它是一个.NET框架类,用于正规化懒惰初始化所需的用例,并提供了开箱即用的功能,因此您不必手动"进行操作.

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".

更多推荐

是否应将此C#代码重构为使用Lazy&lt; T&gt;.课吗?

本文发布于:2023-11-13 23:00:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585557.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:将此   重构   代码   Lazy   课吗

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!