Lazy<T> Classe

Definição

Dá suporte à inicialização lenta.Provides support for lazy initialization.

generic <typename T>
public ref class Lazy
public class Lazy<T>
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class Lazy<T>
type Lazy<'T> = class
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type Lazy<'T> = class
Public Class Lazy(Of T)

Parâmetros de tipo

T

O tipo de objeto que está sendo inicializado sem pressa.The type of object that is being lazily initialized.

Herança
Lazy<T>
Derivado
Atributos

Exemplos

O exemplo a seguir demonstra o uso da Lazy<T> classe para fornecer inicialização lenta com acesso de vários threads.The following example demonstrates the use of the Lazy<T> class to provide lazy initialization with access from multiple threads.

Observação

O exemplo usa o Lazy<T>(Func<T>) Construtor.The example uses the Lazy<T>(Func<T>) constructor. Ele também demonstra o uso do Lazy<T>(Func<T>, Boolean) Construtor (especificando true for isThreadSafe ) e o Lazy<T>(Func<T>, LazyThreadSafetyMode) Construtor (especificando LazyThreadSafetyMode.ExecutionAndPublication for mode ).It also demonstrates the use of the Lazy<T>(Func<T>, Boolean) constructor (specifying true for isThreadSafe) and the Lazy<T>(Func<T>, LazyThreadSafetyMode) constructor (specifying LazyThreadSafetyMode.ExecutionAndPublication for mode). Para alternar para um Construtor diferente, basta alterar quais construtores foram comentados.To switch to a different constructor, just change which constructors are commented out.

Para obter um exemplo que demonstra o cache de exceções usando os mesmos construtores, consulte o Lazy<T>(Func<T>) Construtor.For an example that demonstrates exception caching using the same constructors, see the Lazy<T>(Func<T>) constructor.

O exemplo define uma classe LargeObject que será inicializada lentamente por um dos vários threads.The example defines a LargeObject class that will be initialized lazily by one of several threads. As quatro seções-chave do código ilustram a criação do inicializador, o método de fábrica, a inicialização real e o construtor da LargeObject classe, que exibe uma mensagem quando o objeto é criado.The four key sections of code illustrate the creation of the initializer, the factory method, the actual initialization, and the constructor of the LargeObject class, which displays a message when the object is created. No início do método Main, o exemplo cria o inicializador thread-safe lento para LargeObject:At the beginning of the Main method, the example creates the thread-safe lazy initializer for LargeObject:

lazyLargeObject = new Lazy<LargeObject>(InitLargeObject);

// The following lines show how to use other constructors to achieve exactly the
// same result as the previous line:
//lazyLargeObject = new Lazy<LargeObject>(InitLargeObject, true);
//lazyLargeObject = new Lazy<LargeObject>(InitLargeObject,
//                               LazyThreadSafetyMode.ExecutionAndPublication);
lazyLargeObject = New Lazy(Of LargeObject)(AddressOf InitLargeObject)

' The following lines show how to use other constructors to achieve exactly the
' same result as the previous line: 
'lazyLargeObject = New Lazy(Of LargeObject)(AddressOf InitLargeObject, True)
'lazyLargeObject = New Lazy(Of LargeObject)(AddressOf InitLargeObject, _
'                               LazyThreadSafetyMode.ExecutionAndPublication)

O método Factory mostra a criação do objeto, com um espaço reservado para inicialização adicional:The factory method shows the creation of the object, with a placeholder for further initialization:

static LargeObject InitLargeObject()
{
    LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId);
    // Perform additional initialization here.
    return large;
}
Private Shared Function InitLargeObject() As LargeObject
    Dim large As New LargeObject(Thread.CurrentThread.ManagedThreadId)
    ' Perform additional initialization here.
    Return large
End Function

Observe que as duas primeiras seções de código podem ser combinadas usando uma função lambda, como mostrado aqui:Note that the first two code sections could be combined by using a lambda function, as shown here:

lazyLargeObject = new Lazy<LargeObject>(() =>
{
    LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId);
    // Perform additional initialization here.
    return large;
});
lazyLargeObject = New Lazy(Of LargeObject)(Function () 
    Dim large As New LargeObject(Thread.CurrentThread.ManagedThreadId) 
    ' Perform additional initialization here.
    Return large
End Function)

O exemplo pausa, para indicar que um período indeterminado pode decorrer antes que ocorra a inicialização lenta.The example pauses, to indicate that an indeterminate period may elapse before lazy initialization occurs. Quando você pressiona a tecla Enter , o exemplo cria e inicia três threads.When you press the Enter key, the example creates and starts three threads. O ThreadProc método usado por todos os três threads chama a Value propriedade.The ThreadProc method that's used by all three threads calls the Value property. Na primeira vez que isso acontecer, a LargeObject instância será criada:The first time this happens, the LargeObject instance is created:

LargeObject large = lazyLargeObject.Value;

// IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the
//            object after creation. You must lock the object before accessing it,
//            unless the type is thread safe. (LargeObject is not thread safe.)
lock(large)
{
    large.Data[0] = Thread.CurrentThread.ManagedThreadId;
    Console.WriteLine("Initialized by thread {0}; last used by thread {1}.",
        large.InitializedBy, large.Data[0]);
}
Dim large As LargeObject = lazyLargeObject.Value

' IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the  
'            object after creation. You must lock the object before accessing it,
'            unless the type is thread safe. (LargeObject is not thread safe.)
SyncLock large
    large.Data(0) = Thread.CurrentThread.ManagedThreadId
    Console.WriteLine("Initialized by thread {0}; last used by thread {1}.", _
        large.InitializedBy, large.Data(0))
End SyncLock

O construtor da LargeObject classe, que inclui a última seção de chave do código, exibe uma mensagem e registra a identidade do thread de inicialização.The constructor of the LargeObject class, which includes the last key section of code, displays a message and records the identity of the initializing thread. A saída do programa aparece no final da listagem de código completa.The output from the program appears at the end of the full code listing.

int initBy = 0;
public LargeObject(int initializedBy)
{
    initBy = initializedBy;
    Console.WriteLine("LargeObject was created on thread id {0}.", initBy);
}
Private initBy As Integer = 0
Public Sub New(ByVal initializedBy As Integer)
    initBy = initializedBy
    Console.WriteLine("LargeObject was created on thread id {0}.", initBy)
End Sub

Observação

Para simplificar, este exemplo usa uma instância global de Lazy<T>, e todos os métodos são static (Shared no Visual Basic).For simplicity, this example uses a global instance of Lazy<T>, and all the methods are static (Shared in Visual Basic). Estes não são requisitos para o uso da inicialização lenta.These are not requirements for the use of lazy initialization.

using System;
using System.Threading;

class Program
{
    static Lazy<LargeObject> lazyLargeObject = null;

    static LargeObject InitLargeObject()
    {
        LargeObject large = new LargeObject(Thread.CurrentThread.ManagedThreadId);
        // Perform additional initialization here.
        return large;
    }

    static void Main()
    {
        // The lazy initializer is created here. LargeObject is not created until the
        // ThreadProc method executes.
        lazyLargeObject = new Lazy<LargeObject>(InitLargeObject);

        // The following lines show how to use other constructors to achieve exactly the
        // same result as the previous line:
        //lazyLargeObject = new Lazy<LargeObject>(InitLargeObject, true);
        //lazyLargeObject = new Lazy<LargeObject>(InitLargeObject,
        //                               LazyThreadSafetyMode.ExecutionAndPublication);

        Console.WriteLine(
            "\r\nLargeObject is not created until you access the Value property of the lazy" +
            "\r\ninitializer. Press Enter to create LargeObject.");
        Console.ReadLine();

        // Create and start 3 threads, each of which uses LargeObject.
        Thread[] threads = new Thread[3];
        for (int i = 0; i < 3; i++)
        {
            threads[i] = new Thread(ThreadProc);
            threads[i].Start();
        }

        // Wait for all 3 threads to finish.
        foreach (Thread t in threads)
        {
            t.Join();
        }

        Console.WriteLine("\r\nPress Enter to end the program");
        Console.ReadLine();
    }

    static void ThreadProc(object state)
    {
        LargeObject large = lazyLargeObject.Value;

        // IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the
        //            object after creation. You must lock the object before accessing it,
        //            unless the type is thread safe. (LargeObject is not thread safe.)
        lock(large)
        {
            large.Data[0] = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("Initialized by thread {0}; last used by thread {1}.",
                large.InitializedBy, large.Data[0]);
        }
    }
}

class LargeObject
{
    public int InitializedBy { get { return initBy; } }

    int initBy = 0;
    public LargeObject(int initializedBy)
    {
        initBy = initializedBy;
        Console.WriteLine("LargeObject was created on thread id {0}.", initBy);
    }

    public long[] Data = new long[100000000];
}

/* This example produces output similar to the following:

LargeObject is not created until you access the Value property of the lazy
initializer. Press Enter to create LargeObject.

LargeObject was created on thread id 3.
Initialized by thread 3; last used by thread 3.
Initialized by thread 3; last used by thread 4.
Initialized by thread 3; last used by thread 5.

Press Enter to end the program
 */
Imports System.Threading

Friend Class Program
    Private Shared lazyLargeObject As Lazy(Of LargeObject) = Nothing

    Private Shared Function InitLargeObject() As LargeObject
        Dim large As New LargeObject(Thread.CurrentThread.ManagedThreadId)
        ' Perform additional initialization here.
        Return large
    End Function


    Shared Sub Main()
        ' The lazy initializer is created here. LargeObject is not created until the 
        ' ThreadProc method executes.
        lazyLargeObject = New Lazy(Of LargeObject)(AddressOf InitLargeObject)

        ' The following lines show how to use other constructors to achieve exactly the
        ' same result as the previous line: 
        'lazyLargeObject = New Lazy(Of LargeObject)(AddressOf InitLargeObject, True)
        'lazyLargeObject = New Lazy(Of LargeObject)(AddressOf InitLargeObject, _
        '                               LazyThreadSafetyMode.ExecutionAndPublication)


        Console.WriteLine(vbCrLf & _
            "LargeObject is not created until you access the Value property of the lazy" _
            & vbCrLf & "initializer. Press Enter to create LargeObject.")
        Console.ReadLine()

        ' Create and start 3 threads, each of which uses LargeObject.
        Dim threads(2) As Thread
        For i As Integer = 0 To 2
            threads(i) = New Thread(AddressOf ThreadProc)
            threads(i).Start()
        Next i

        ' Wait for all 3 threads to finish. 
        For Each t As Thread In threads
            t.Join()
        Next t

        Console.WriteLine(vbCrLf & "Press Enter to end the program")
        Console.ReadLine()
    End Sub


    Private Shared Sub ThreadProc(ByVal state As Object)
        Dim large As LargeObject = lazyLargeObject.Value

        ' IMPORTANT: Lazy initialization is thread-safe, but it doesn't protect the  
        '            object after creation. You must lock the object before accessing it,
        '            unless the type is thread safe. (LargeObject is not thread safe.)
        SyncLock large
            large.Data(0) = Thread.CurrentThread.ManagedThreadId
            Console.WriteLine("Initialized by thread {0}; last used by thread {1}.", _
                large.InitializedBy, large.Data(0))
        End SyncLock
    End Sub
End Class

Friend Class LargeObject
    Public ReadOnly Property InitializedBy() As Integer
        Get
            Return initBy
        End Get
    End Property

    Private initBy As Integer = 0
    Public Sub New(ByVal initializedBy As Integer)
        initBy = initializedBy
        Console.WriteLine("LargeObject was created on thread id {0}.", initBy)
    End Sub

    Public Data(99999999) As Long
End Class

' This example produces output similar to the following:
'
'LargeObject is not created until you access the Value property of the lazy
'initializer. Press Enter to create LargeObject.
'
'LargeObject was created on thread id 3.
'Initialized by thread 3; last used by thread 3.
'Initialized by thread 3; last used by thread 5.
'Initialized by thread 3; last used by thread 4.
'
'Press Enter to end the program
' 

Comentários

Use a inicialização lenta para adiar a criação de um objeto grande ou intensivo de recursos, ou a execução de uma tarefa de uso intensivo de recursos, especialmente quando tal criação ou execução não puder ocorrer durante o tempo de vida do programa.Use lazy initialization to defer the creation of a large or resource-intensive object, or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

Para se preparar para a inicialização lenta, você cria uma instância do Lazy<T> .To prepare for lazy initialization, you create an instance of Lazy<T>. O argumento de tipo do Lazy<T> objeto que você cria especifica o tipo do objeto que você deseja inicializar lentamente.The type argument of the Lazy<T> object that you create specifies the type of the object that you want to initialize lazily. O construtor que você usa para criar o Lazy<T> objeto determina as características da inicialização.The constructor that you use to create the Lazy<T> object determines the characteristics of the initialization. A inicialização lenta ocorre na primeira vez que a propriedade Lazy<T>.Value é acessada.Lazy initialization occurs the first time the Lazy<T>.Value property is accessed.

Na maioria dos casos, a escolha de um Construtor depende de suas respostas a duas perguntas:In most cases, choosing a constructor depends on your answers to two questions:

  • O objeto inicializado lentamente será acessado de mais de um thread?Will the lazily initialized object be accessed from more than one thread? Nesse caso, o Lazy<T> objeto pode criá-lo em qualquer thread.If so, the Lazy<T> object might create it on any thread. Você pode usar um dos construtores simples cujo comportamento padrão é criar um objeto thread-safe, de Lazy<T> modo que apenas uma instância do objeto com instância lenta seja criada, independentemente de quantos threads tentarem acessá-lo.You can use one of the simple constructors whose default behavior is to create a thread-safe Lazy<T> object, so that only one instance of the lazily instantiated object is created no matter how many threads try to access it. Para criar um Lazy<T> objeto que não é thread-safe, você deve usar um construtor que permita que você não especifique nenhuma segurança de thread.To create a Lazy<T> object that is not thread safe, you must use a constructor that enables you to specify no thread safety.

    Cuidado

    Tornar o Lazy<T> thread de objeto seguro não protege o objeto inicializado lentamente.Making the Lazy<T> object thread safe does not protect the lazily initialized object. Se vários threads puderem acessar o objeto inicializado lentamente, você deverá tornar suas propriedades e seus métodos seguros para acesso multithread.If multiple threads can access the lazily initialized object, you must make its properties and methods safe for multithreaded access.

  • A inicialização lenta requer muito código ou o objeto inicializado lentamente tem um construtor sem parâmetros que faz tudo o que você precisa e não lança exceções?Does lazy initialization require a lot of code, or does the lazily initialized object have a parameterless constructor that does everything you need and doesn't throw exceptions? Se você precisar escrever o código de inicialização ou se as exceções precisarem ser manipuladas, use um dos construtores que usa um método de fábrica.If you need to write initialization code or if exceptions need to be handled, use one of the constructors that takes a factory method. Escreva o código de inicialização no método de fábrica.Write your initialization code in the factory method.

A tabela a seguir mostra qual Construtor escolher, com base nesses dois fatores:The following table shows which constructor to choose, based on these two factors:

O objeto será acessado porObject will be accessed by Se nenhum código de inicialização for necessário (Construtor sem parâmetros), useIf no initialization code is required (parameterless constructor), use Se o código de inicialização for necessário, useIf initialization code is required, use
Vários threadsMultiple threads Lazy<T>() Lazy<T>(Func<T>)
Um threadOne thread Lazy<T>(Boolean) com isThreadSafe definido como false .Lazy<T>(Boolean) with isThreadSafe set to false. Lazy<T>(Func<T>, Boolean) com isThreadSafe definido como false .Lazy<T>(Func<T>, Boolean) with isThreadSafe set to false.

Você pode usar uma expressão lambda para especificar o método de fábrica.You can use a lambda expression to specify the factory method. Isso mantém todo o código de inicialização em um único lugar.This keeps all the initialization code in one place. A expressão lambda captura o contexto, incluindo os argumentos que você passa para o construtor do objeto inicializado lentamente.The lambda expression captures the context, including any arguments you pass to the lazily initialized object's constructor.

Cache de exceção Quando você usa métodos de fábrica, as exceções são armazenadas em cache.Exception caching When you use factory methods, exceptions are cached. Ou seja, se o método de fábrica lançar uma exceção na primeira vez que um thread tentar acessar a Value Propriedade do Lazy<T> objeto, a mesma exceção será lançada em todas as tentativas subsequentes.That is, if the factory method throws an exception the first time a thread tries to access the Value property of the Lazy<T> object, the same exception is thrown on every subsequent attempt. Isso garante que cada chamada para a Value Propriedade produza o mesmo resultado e evita erros sutis que podem surgir se threads diferentes obtiverem resultados diferentes.This ensures that every call to the Value property produces the same result and avoids subtle errors that might arise if different threads get different results. O Lazy<T> se destaca por um real T que, de outra forma, teria sido inicializado em algum ponto anterior, geralmente durante a inicialização.The Lazy<T> stands in for an actual T that otherwise would have been initialized at some earlier point, usually during startup. Uma falha nesse ponto anterior geralmente é fatal.A failure at that earlier point is usually fatal. Se houver um potencial para uma falha recuperável, recomendamos que você crie a lógica de repetição na rotina de inicialização (nesse caso, o método de fábrica), assim como você faria se não estivesse usando a inicialização lenta.If there is a potential for a recoverable failure, we recommend that you build the retry logic into the initialization routine (in this case, the factory method), just as you would if you weren't using lazy initialization.

Alternativa ao bloqueio Em determinadas situações, talvez você queira evitar a sobrecarga do comportamento de Lazy<T> bloqueio padrão do objeto.Alternative to locking In certain situations, you might want to avoid the overhead of the Lazy<T> object's default locking behavior. Em raras situações, pode haver um potencial para deadlocks.In rare situations, there might be a potential for deadlocks. Nesses casos, você pode usar o Lazy<T>(LazyThreadSafetyMode) Construtor ou Lazy<T>(Func<T>, LazyThreadSafetyMode) e especificar LazyThreadSafetyMode.PublicationOnly .In such cases, you can use the Lazy<T>(LazyThreadSafetyMode) or Lazy<T>(Func<T>, LazyThreadSafetyMode) constructor, and specify LazyThreadSafetyMode.PublicationOnly. Isso permite que o Lazy<T> objeto crie uma cópia do objeto inicializado lentamente em cada um dos vários threads se os threads chamarem a Value Propriedade simultaneamente.This enables the Lazy<T> object to create a copy of the lazily initialized object on each of several threads if the threads call the Value property simultaneously. O Lazy<T> objeto garante que todos os threads usem a mesma instância do objeto inicializado lentamente e descarte as instâncias que não são usadas.The Lazy<T> object ensures that all threads use the same instance of the lazily initialized object and discards the instances that are not used. Portanto, o custo da redução da sobrecarga de bloqueio é que o programa pode, às vezes, criar e descartar cópias extras de um objeto caro.Thus, the cost of reducing the locking overhead is that your program might sometimes create and discard extra copies of an expensive object. Na maioria dos casos, isso é improvável.In most cases, this is unlikely. Os exemplos para os Lazy<T>(LazyThreadSafetyMode) Lazy<T>(Func<T>, LazyThreadSafetyMode) construtores e demonstram esse comportamento.The examples for the Lazy<T>(LazyThreadSafetyMode) and Lazy<T>(Func<T>, LazyThreadSafetyMode) constructors demonstrate this behavior.

Importante

Quando você especifica LazyThreadSafetyMode.PublicationOnly , as exceções nunca são armazenadas em cache, mesmo se você especificar um método de fábrica.When you specify LazyThreadSafetyMode.PublicationOnly, exceptions are never cached, even if you specify a factory method.

Construtores equivalentes Além de habilitar o uso de LazyThreadSafetyMode.PublicationOnly , os Lazy<T>(LazyThreadSafetyMode) construtores e Lazy<T>(Func<T>, LazyThreadSafetyMode) podem duplicar a funcionalidade dos outros construtores.Equivalent constructors In addition to enabling the use of LazyThreadSafetyMode.PublicationOnly, the Lazy<T>(LazyThreadSafetyMode) and Lazy<T>(Func<T>, LazyThreadSafetyMode) constructors can duplicate the functionality of the other constructors. A tabela a seguir mostra os valores de parâmetro que produzem o comportamento equivalente.The following table shows the parameter values that produce equivalent behavior.

Para criar um Lazy<T> objeto que éTo create a Lazy<T> object that is Para construtores que têm um LazyThreadSafetyMode mode parâmetro, defina mode comoFor constructors that have a LazyThreadSafetyMode mode parameter, set mode to Para construtores que têm um parâmetro booliano isThreadSafe , defina isThreadSafe comoFor constructors that have a Boolean isThreadSafe parameter, set isThreadSafe to Para construtores sem parâmetros de segurança de threadFor constructors with no thread safety parameters
Totalmente seguro para thread; usa o bloqueio para garantir que apenas um thread inicialize o valor.Fully thread safe; uses locking to ensure that only one thread initializes the value. ExecutionAndPublication true Todos esses construtores são totalmente seguros para thread.All such constructors are fully thread safe.
Sem segurança de thread.Not thread safe. None false Não aplicável.Not applicable.
Totalmente seguro para thread; os threads corridas para inicializar o valor.Fully thread safe; threads race to initialize the value. PublicationOnly Não aplicável.Not applicable. Não aplicável.Not applicable.

Outros recursos Para obter informações sobre o uso de Lazy<T> com campos estáticos de thread ou como o armazenamento de backup para propriedades, consulte inicialização lenta.Other capabilities For information about the use of Lazy<T> with thread-static fields, or as the backing store for properties, see Lazy Initialization.

Construtores

Lazy<T>()

Inicializa uma nova instância da classe Lazy<T>.Initializes a new instance of the Lazy<T> class. Quando ocorre a inicialização lenta, o construtor sem parâmetros do tipo de destino é usado.When lazy initialization occurs, the parameterless constructor of the target type is used.

Lazy<T>(Boolean)

Inicializa uma nova instância da classe Lazy<T>.Initializes a new instance of the Lazy<T> class. Quando ocorre a inicialização lenta, o construtor sem parâmetros do tipo de destino e o modo de inicialização especificado são usados.When lazy initialization occurs, the parameterless constructor of the target type and the specified initialization mode are used.

Lazy<T>(Func<T>)

Inicializa uma nova instância da classe Lazy<T>.Initializes a new instance of the Lazy<T> class. Quando ocorre uma inicialização lenta, a função de inicialização especificada é usada.When lazy initialization occurs, the specified initialization function is used.

Lazy<T>(Func<T>, Boolean)

Inicializa uma nova instância da classe Lazy<T>.Initializes a new instance of the Lazy<T> class. Quando ocorre a inicialização lenta, a função de inicialização especificada e o modo de inicialização são usados.When lazy initialization occurs, the specified initialization function and initialization mode are used.

Lazy<T>(Func<T>, LazyThreadSafetyMode)

Inicializa uma nova instância da classe Lazy<T> que usa a função de inicialização especificada e o modo de segurança do thread.Initializes a new instance of the Lazy<T> class that uses the specified initialization function and thread-safety mode.

Lazy<T>(LazyThreadSafetyMode)

Inicializa uma nova instância da classe Lazy<T> que usa o construtor sem parâmetros T e o modo de acesso thread-safe especificado.Initializes a new instance of the Lazy<T> class that uses the parameterless constructor of T and the specified thread-safety mode.

Lazy<T>(T)

Inicializa uma nova instância da classe Lazy<T> que usa um valor especificado pré-inicializado.Initializes a new instance of the Lazy<T> class that uses a preinitialized specified value.

Propriedades

IsValueCreated

Obtém um valor que indica se um valor foi criado para essa instância Lazy<T>.Gets a value that indicates whether a value has been created for this Lazy<T> instance.

Value

Obtém o valor de inicialização ociosa da instância Lazy<T> atual.Gets the lazily initialized value of the current Lazy<T> instance.

Métodos

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
ToString()

Cria e retorna uma representação de cadeia de caracteres da propriedade Value para esta instância.Creates and returns a string representation of the Value property for this instance.

Aplica-se a

Acesso thread-safe

Por padrão, todos os membros públicos e protegidos da Lazy<T> classe são thread-safe e podem ser usados simultaneamente de vários threads.By default, all public and protected members of the Lazy<T> class are thread safe and may be used concurrently from multiple threads. Essas garantias de segurança de thread podem ser removidas opcionalmente e por instância, usando parâmetros para os construtores do tipo.These thread-safety guarantees may be removed optionally and per instance, using parameters to the type's constructors.

Confira também