Apidcloud

Async Singleton 2

Feb 11th, 2016
113
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
  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.         private Task<MyClass> Initialization { get; set; }
  18.  
  19.         #endregion
  20.  
  21.         #region Constructors
  22.  
  23.         private MyClass ()
  24.         {
  25.             Initialization = InitializeAsync();
  26.         }
  27.  
  28.         #endregion
  29.  
  30.         #region Methods
  31.  
  32.         public static MyClass Instance()
  33.         {
  34.             // Shouldn't I check if Initialization is null? Would that be thread safe?
  35.             return _instance;
  36.         }
  37.  
  38.         public static Task<MyClass> InstanceAsync()
  39.         {
  40.             return _instance.Initialization;
  41.         }
  42.  
  43.         private async Task<MyClass> InitializeAsync()
  44.         {
  45.             // Call async method
  46.             await DoSomethingAsync();
  47.  
  48.             // Do our own initialization (synchronous or asynchronous).
  49.             await Task.Delay(100);
  50.  
  51.             return this;
  52.         }
  53.  
  54.         private async Task DoSomethingAsync()
  55.         {
  56.             await Task.Delay(10000);
  57.             // await Something();
  58.         }
  59.  
  60.         #endregion
  61.  
  62.     }
  63. }
RAW Paste Data