以下是最常见的方案:
-
Orders 对象声明为延迟初始化,可以避免在不使用该对象的情况下浪费系统资源。
-
通过将不必要的对象的初始化延迟到已创建必要的对象之后,可以提高程序的启动性能。
及其相关的类型还支持线程安全,并提供一致的异常传播策略。
下表列出了 .NET Framework 版本 4 提供的、可在不同方案中启用延迟初始化的类型。
|
类型 |
说明 |
|---|---|
|
一个包装类,可为任意类库或用户定义的类型提供延迟初始化语义。 |
|
|
每个线程都可以访问自己的唯一值。 |
|
|
Shared)方法,此方法不需要类开销。 |
// Initialize by using default Lazy<T> constructor. The
// Orders array itself is not created yet.
Lazy<Orders> _orders = new Lazy<Orders>();
> 构造函数中传递一个委托,用于在创建时调用包装类的特定构造函数重载,并执行所需的任何其他初始化步骤,如以下示例中所示。
// Initialize by invoking a specific constructor on Order when Value
// property is accessed
Lazy<Orders> _orders = new Lazy<Orders>(() => new Orders(100));
在第一次访问包装类型时,将会创建并返回该包装类型,并将其存储起来以备任何将来的访问。
// We need to create the array only if displayOrders is true
if (displayOrders == true)
{
DisplayOrders(_orders.Value.OrderData);
}
else
{
// Don't waste resources getting order data.
}
但是,可以使用新的参数通过再次调用变量构造函数来创建新的变量。
_orders = new Lazy<Orders>(() => new Orders(10));
Orders。
线程安全初始化
true。
Lazy<int> 实例对于三个不同的线程具有相同的值。
// Initialize the integer to the managed thread id of the
// first thread that accesses the Value property.
Lazy<int> number = new Lazy<int>(() => Thread.CurrentThread.ManagedThreadId);
Thread t1 = new Thread(() => Console.WriteLine("number on t1 = {0} ThreadID = {1}",
number.Value, Thread.CurrentThread.ManagedThreadId));
t1.Start();
Thread t2 = new Thread(() => Console.WriteLine("number on t2 = {0} ThreadID = {1}",
number.Value, Thread.CurrentThread.ManagedThreadId));
t2.Start();
Thread t3 = new Thread(() => Console.WriteLine("number on t3 = {0} ThreadID = {1}", number.Value,
Thread.CurrentThread.ManagedThreadId));
t3.Start();
// Ensure that thread IDs are not recycled if the
// first thread completes before the last one starts.
t1.Join();
t2.Join();
t3.Join();
/* Sample Output:
number on t1 = 11 ThreadID = 11
number on t3 = 11 ThreadID = 13
number on t2 = 11 ThreadID = 12
Press any key to exit.
*/
> 类型,如本主题后面所述。
实现延迟初始化属性
class Customer
{
private Lazy<Orders> _orders;
public string CustomerID {get; private set;}
public Customer(string id)
{
CustomerID = id;
_orders = new Lazy<Orders>(() =>
{
// You can specify any additonal
// initialization steps here.
return new Orders(this.CustomerID);
});
}
public Orders MyOrders
{
get
{
// Orders is created on first access here.
return _orders.Value;
}
}
}
set 访问器,则可能需要额外的协调。
更多信息参考:http://msdn.microsoft.com/zh-cn/library/dd997286.aspx