Procédure : Effectuer une initialisation tardive d’objets
La classe System.Lazy<T> simplifie les opérations d’initialisation tardive et d’instanciation des objets. L’initialisation des objets de manière tardive vous évite d’avoir à créer inutilement des objets non nécessaires, ou vous permet de différer l’initialisation des objets jusqu’à ce qu’ils commencent à être utilisés. Pour plus d’informations, consultez Initialisation tardive.
Exemple 1
L’exemple suivant montre comment initialiser une valeur avec Lazy<T>. Il suppose que la variable tardive peut ne pas être nécessaire, selon que la variable someCondition
est définie sur true ou false dans un autre code.
Dim someCondition As Boolean = False
Sub Main()
'Initializing a value with a big computation, computed in parallel
Dim _data As Lazy(Of Integer) = New Lazy(Of Integer)(Function()
Dim result =
ParallelEnumerable.Range(0, 1000).
Aggregate(Function(x, y)
Return x + y
End Function)
Return result
End Function)
' do work that may or may not set someCondition to True
' ...
' Initialize the data only if needed
If someCondition = True Then
If (_data.Value > 100) Then
Console.WriteLine("Good data")
End If
End If
End Sub
static bool someCondition = false;
//Initializing a value with a big computation, computed in parallel
Lazy<int> _data = new Lazy<int>(delegate
{
return ParallelEnumerable.Range(0, 1000).
Select(i => Compute(i)).Aggregate((x,y) => x + y);
}, LazyThreadSafetyMode.ExecutionAndPublication);
// Do some work that may or may not set someCondition to true.
// ...
// Initialize the data only if necessary
if (someCondition)
{
if (_data.Value > 100)
{
Console.WriteLine("Good data");
}
}
Exemple 2
L’exemple suivant montre comment utiliser la classe System.Threading.ThreadLocal<T> pour initialiser un type qui est visible uniquement pour l’instance d’objet qui est exécutée sur le thread actuel.
//Initializing a value per thread, per instance
ThreadLocal<int[][]> _scratchArrays =
new ThreadLocal<int[][]>(InitializeArrays);
// . . .
static int[][] InitializeArrays () {return new int[][]}
// . . .
// use the thread-local data
int i = 8;
int [] tempArr = _scratchArrays.Value[i];
'Initializing a value per thread, per instance
Dim _scratchArrays =
New ThreadLocal(Of Integer()())(Function() InitializeArrays())
' use the thread-local data
Dim tempArr As Integer() = _scratchArrays.Value(i)
' ...
End Sub
Function InitializeArrays() As Integer()()
Dim result(10)() As Integer
' Initialize the arrays on the current thread.
' ...
Return result
End Function
Voir aussi
Commentaires
https://aka.ms/ContentUserFeedback.
Bientôt disponible : Tout au long de 2024, nous allons supprimer progressivement GitHub Issues comme mécanisme de commentaires pour le contenu et le remplacer par un nouveau système de commentaires. Pour plus d’informations, consultezEnvoyer et afficher des commentaires pour