Laze는 초기화를 나중에 미룰 때 한다 .
여러 곳에서 Laze 객체에 접근할 수 있기 때문에
직접 안전한 Thread 접근을 위해 Lock 이나 volatile, boolean 을 같이 사용하여 안전한 접근을 만들어줘야한다.
예제를 보면 정확히 알 수 있는데 아래에 Lazy<Test> lazy = new Lazy<Test>(); 객체 생성 구문에서 Test는 생성되지 않는다.
laze.Value를 호출함으로써 Test가 생성되고 추가적으로 객체 생성 구문에 클래스의 초기값을 설정할 수도있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | class Program { static void Main(string[] args) { // Create Lazy. Lazy<Test> lazy = new Lazy<Test>(); // Show that IsValueCreated is false. Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated); // Get the Value. // ... This executes Test(). Test test = lazy.Value; // Show the IsValueCreated is true. Console.WriteLine("IsValueCreated = {0}", lazy.IsValueCreated); // The object can be used. Console.WriteLine("Length = {0}", test.Length); } class Test { int[] _array; public Test() { Console.WriteLine("Test()"); _array = new int[10]; } public int Length { get { return _array.Length; } } } } | cs |
'.NET 개발 > C#' 카테고리의 다른 글
Task<T> Class (0) | 2015.08.10 |
---|---|
Task Class 비동기 (0) | 2015.08.10 |
Thread Class (0) | 2015.07.31 |
.Net Remoting (0) | 2015.07.30 |
Inversion of Control(IOC), Dependency Injection(DI) (0) | 2015.07.13 |