
The Lazy class is a nice little tool that was added in .NET 4. Like the name implies, it helps with lazy initialization of data. That way the data is initialized when you ask for it instead of when you class is constructed.
This is useful when programming with Vault because there are many times you need to look up server data and store it. For example, let’s say you have a custom command that makes use of a specific property definition. At some point you need to get the PropDef object from Vault server, but when is the best time? You don’t want to do it during OnLogOn because it costs time to look up the PropDef, and the user may not run your command. The best time to get the PropDef is the first time your command is run. Then you store the object so that subsequent calls don’t have to make the same server request again.
Here is how you would look up the Author PropDef with Lazy:
|
' VB.NET// C# public class MyClass { private Lazy<PropDef> m_authorPropDef; public PropDef AuthorPropDef { get { return m_authorPropDef.Value; } }
public MyClass() { m_authorPropDef = new Lazy<PropDef>(GetAuthorPropDef); }
private PropDef GetAuthorPropDef() { PropDef[] defs = WebSvcMgr.PropertyService.FindPropertyDefinitionsBySystemNames(
if (defs == null || defs.Length != 1 || defs[0].Id < 0) throw new Exception("Error looking up property definition");
return defs[0]; } } |
|
' VB.NET Public Class [MyClass] Private m_authorPropDef As Lazy(Of PropDef) Public ReadOnly Property AuthorPropDef() As PropDef Get Return m_authorPropDef.Value End Get End Property
Public Sub New() m_authorPropDef = New Lazy(Of PropDef)(AddressOf GetAuthorPropDef) End Sub
Private Function GetAuthorPropDef() As PropDef Dim defs As PropDef() =
If defs Is Nothing OrElse defs.Length <> 1 OrElse defs(0).Id < 0 Then Throw New Exception("Error looking up property definition") End If
Return defs(0) End Function End Class |


Leave a Reply