1 //--------------------------------------------------------------------------
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // File: LazyExtensions.cs
7 //--------------------------------------------------------------------------
9 using System.Threading;
10 using System.Threading.Tasks;
14 /// <summary>Extension methods for Lazy.</summary>
15 public static class LazyExtensions
17 /// <summary>Forces value creation of a Lazy instance.</summary>
18 /// <typeparam name="T">Specifies the type of the value being lazily initialized.</typeparam>
19 /// <param name="lazy">The Lazy instance.</param>
20 /// <returns>The initialized Lazy instance.</returns>
21 public static Lazy<T> Force<T>(this Lazy<T> lazy)
23 var ignored = lazy.Value;
27 /// <summary>Retrieves the value of a Lazy asynchronously.</summary>
28 /// <typeparam name="T">Specifies the type of the value being lazily initialized.</typeparam>
29 /// <param name="lazy">The Lazy instance.</param>
30 /// <returns>A Task representing the Lazy's value.</returns>
31 public static Task<T> GetValueAsync<T>(this Lazy<T> lazy)
33 return Task.Factory.StartNew(() => lazy.Value);
36 /// <summary>Creates a Lazy that's already been initialized to a specified value.</summary>
37 /// <typeparam name="T">The type of the data to be initialized.</typeparam>
38 /// <param name="value">The value with which to initialize the Lazy instance.</param>
39 /// <returns>The initialized Lazy.</returns>
40 public static Lazy<T> Create<T>(T value)
42 return new Lazy<T>(() => value, false).Force();