我有一个带有一些静态属性的静态类.我在静态构造函数中初始化了所有这些,但后来意识到它是浪费的,我应该在需要时懒惰加载每个属性.所以我切换到使用该System.Lazy<T>类型来完成所有脏工作,并告诉它不要使用它的任何线程安全功能,因为在我的情况下执行始终是单线程的.
我最后得到了以下课程:
public static class Queues
{
private static readonly Lazy<Queue> g_Parser = new Lazy<Queue>(() => new Queue(Config.ParserQueueName), false);
private static readonly Lazy<Queue> g_Distributor = new Lazy<Queue>(() => new Queue(Config.DistributorQueueName), false);
private static readonly Lazy<Queue> g_ConsumerAdapter = new Lazy<Queue>(() => new Queue(Config.ConsumerAdaptorQueueName), false);
public static Queue Parser { get { return g_Parser.Value; } }
public static Queue Distributor { get { return g_Distributor.Value; } }
public static Queue ConsumerAdapter { get { return g_ConsumerAdapter.Value; } }
}
Run Code Online (Sandbox Code Playgroud)
在调试时,我注意到了一条我从未见过的消息: …
c# lazy-loading visual-studio-2010 visual-studio visual-studio-debugging