是否应将此C#代码重构为使用Lazy< T>.课吗? [英] Should this C# code be refactored to use the Lazy<T> class instead?

查看:61
本文介绍了是否应将此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;.课吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆