Advertisement
Guest User

Untitled

a guest
Jan 18th, 2021
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.48 KB | None | 0 0
  1. class SomeClass
  2. {
  3.     private Task<ValueType> foo = null;
  4.     private readonly SemaphoreSlim sem = new SemaphoreSlim();
  5.    
  6.     /* ... */
  7.  
  8.     Task<ValueType> getFoo()
  9.     {
  10.         var foo = this.foo;
  11.         if (!foo) {
  12.             return asyncInitFoo();
  13.         }
  14.  
  15.         return foo;
  16.     }
  17.  
  18.     async Task<ValueType> asyncInitFoo()
  19.     {
  20.         await sem.WaitAsync();
  21.         try
  22.         {
  23.             if (foo == null) {
  24.                 foo = Task.FromResult(/* ... */);
  25.             }
  26.  
  27.             return foo;
  28.         }
  29.         finally
  30.         {
  31.             sem.Release();
  32.         }
  33.     }
  34.  
  35.     /* ... */
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement