【发布时间】:2008-11-11 01:44:24
【问题描述】:
面向未来读者的更新:当 .NET 4 发布时,来自 CTP 的 LazyInit<T> 将被重命名为 Lazy<T> 并将从结构更改为类,所以很少这将适用,除非作为说明为什么如果您不小心可变结构可能会出现问题。
我一直在 Parallel Extensions June CTP 中试验 LazyInit,我希望下面的代码会打印一千次相同的 Guid,但它会打印出一千个不同的 Guid。显然,我在这里遗漏了一些关于 LazyInit 应该如何工作的明显内容,如果有人能指出它是什么,我将不胜感激。
using System;
using System.Diagnostics;
using System.Threading;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
for (int i=0; i < 1000; i++)
{
Console.WriteLine(TestClass.Instance.Id);
}
Console.Write("Press any key to continue:");
Console.ReadKey();
}
private class TestClass
{
private static readonly LazyInit<TestClass> _instance = new LazyInit<TestClass>(() => new TestClass(), LazyInitMode.EnsureSingleExecution);
public static TestClass Instance
{
get { return _instance.Value; }
}
private TestClass()
{
Debug.WriteLine("TestClass Constructor");
Id = Guid.NewGuid();
}
public Guid Id { get; private set; }
}
}
}
【问题讨论】: