All files
[pithos-ms-client] / trunk / Libraries / ParallelExtensionsExtras / Extensions / LazyExtensions.cs
1 //--------------------------------------------------------------------------
2 // 
3 //  Copyright (c) Microsoft Corporation.  All rights reserved. 
4 // 
5 //  File: LazyExtensions.cs
6 //
7 //--------------------------------------------------------------------------
8
9 using System.Threading;
10 using System.Threading.Tasks;
11
12 namespace System
13 {
14     /// <summary>Extension methods for Lazy.</summary>
15     public static class LazyExtensions
16     {
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)
22         {
23             var ignored = lazy.Value;
24             return lazy;
25         }
26
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)
32         {
33             return Task.Factory.StartNew(() => lazy.Value);
34         }
35
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)
41         {
42             return new Lazy<T>(() => value, false).Force();
43         }
44     }
45 }