9

我有以下代码,可以同时通过多个网络请求调用。因此,我不希望第二个+请求命中数据库,而是等到第一个请求。

我应该重构它以使用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
}
4

2 回答 2

15

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

来自MSDN

默认情况下,惰性对象是线程安全的。也就是说,如果构造函数没有指定线程安全的类型,那么它创建的 Lazy 对象是线程安全的。在多线程场景中,第一个访问线程安全 Lazy 对象的 Value 属性的线程会为所有线程上的所有后续访问初始化它,并且所有线程共享相同的数据。因此,哪个线程初始化对象并不重要,竞争条件是良性的。

是的,它不是关键字——它是一个 .NET 框架类,它形式化了延迟初始化经常需要的用例,并提供了开箱即用的功能,因此您不必“手动”进行操作。

于 2011-08-24T01:13:24.277 回答
9

正如@BrokenGlass 指出的那样,它是安全的。但我无法抗拒,不得不做一个测试......

只打印一个线程 id...

private static Lazy<int> lazyInt;

// make it slow
private int fib()
{
    Thread.Sleep(1000);
    return 0;
}

public void Test()
{
    // when run prints the thread id
    lazyInt = new Lazy<int>(
        () =>
        {
            Debug.WriteLine("ID: {0} ", Thread.CurrentThread.ManagedThreadId);
            return fib();
        });

    var t1 = new Thread(() => { var x = lazyInt.Value; });
    var t2 = new Thread(() => { var x = lazyInt.Value; });
    var t3 = new Thread(() => { var x = lazyInt.Value; });

    t1.Start();
    t2.Start();
    t3.Start();

    t1.Join();
    t2.Join();
    t3.Join();
}

但是,哪个更快?从我得到的结果...

执行代码 100 次

[   Lazy: 00:00:01.003   ]
[  Field: 00:00:01.000   ]

执行代码 100000000 次

[   Lazy: 00:00:10.516   ]
[  Field: 00:00:17.969   ]

测试代码:

Performance.Test("Lazy", TestAmount, false,
    () =>
    {
        var laz = lazyInt.Value;
    });

Performance.Test("Field", TestAmount, false,
    () =>
    {
        var laz = FieldInt;
    });

测试方法:

public static void Test(string name, decimal times, bool precompile, Action fn)
{
    if (precompile)
    {
        fn();
    }

    GC.Collect();
    Thread.Sleep(2000);

    var sw = new Stopwatch();

    sw.Start();

    for (decimal i = 0; i < times; ++i)
    {
        fn();
    }

    sw.Stop();

    Console.WriteLine("[{0,15}: {1,-15}]", name, new DateTime(sw.Elapsed.Ticks).ToString("HH:mm:ss.fff"));
}
于 2011-08-24T02:07:20.297 回答