Apidcloud

Async Singleton

Feb 10th, 2016
217
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Threading.Tasks;
  3.  
  4. namespace TestProject
  5. {
  6.     public class MyClass // cant implement IAsyncInitialization, since 'Initialization' property should be private
  7.     {
  8.         #region Fields
  9.  
  10.         // 'eagerly initialized'
  11.         private static readonly MyClass _instance = new MyClass ();
  12.  
  13.         #endregion
  14.  
  15.         #region Properties
  16.  
  17.         #region IAsyncInitialization Implementation
  18.  
  19.         // private instead of public
  20.         private Task Initialization { get; set; }
  21.  
  22.         #endregion
  23.  
  24.         #endregion
  25.  
  26.         #region Constructors
  27.  
  28.         private MyClass ()
  29.         {
  30.             Initialization = InitializeAsync();
  31.         }
  32.  
  33.         #endregion
  34.  
  35.         #region Methods
  36.  
  37.         /// <summary>
  38.         /// The Singleton instance
  39.         /// </summary>
  40.         public static MyClass Instance()
  41.         {
  42.             // Would this be 'await'ed everytime one calls 'MyClass.Instance()' ?
  43.             // await _instance.Initialization; // It would also change the method to 'public static async Task<MyClass> Instance()'
  44.             return _instance;
  45.         }
  46.  
  47.         private async Task InitializeAsync()
  48.         {
  49.             // Call async method
  50.             await DoSomethingAsync();
  51.  
  52.             // Do our own initialization (synchronous or asynchronous).
  53.             await Task.Delay(100);
  54.         }
  55.  
  56.         private async Task DoSomethingAsync()
  57.         {
  58.             // await Something();
  59.         }
  60.  
  61.         #endregion
  62.  
  63.     }
  64. }
RAW Paste Data