Advertisement
Guest User

Untitled

a guest
Mar 18th, 2014
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.90 KB | None | 0 0
  1. void Main()
  2. {
  3.     var alock = new AsyncLock();
  4.     int numberOfTasks = 100000;
  5.     int counterLocked = 0;
  6.     int counterAtomicBegin = 0;
  7.     int counterAtomicEnd = 0;
  8.  
  9.     Task[] tasks = new Task[numberOfTasks];
  10.  
  11.     for (int i = 0; i < numberOfTasks; i++)
  12.     {
  13.         tasks[i] = Task.Run<Task>(async () =>
  14.         {
  15.             Interlocked.Increment(ref counterAtomicBegin);
  16.             using (await alock.LockAsync().ConfigureAwait(false))
  17.             {
  18.                 counterLocked += 1;
  19.             }
  20.             Interlocked.Increment(ref counterAtomicEnd);
  21.         });
  22.     }
  23.  
  24.     bool result = Task.WaitAll(tasks, 10000);
  25.     String.Format("counterLocked={0}; counterAtomicBegin={1}",
  26.         counterLocked, counterAtomicBegin).Dump();
  27. }
  28.  
  29. /// <summary>Wrapper for locking in an asynchronous way.</summary>
  30. public class AsyncLock : IDisposable
  31. {
  32.     /// <summary>Gets a semaphore that can be used to synchronize access.</summary>
  33.     /// <returns>A semaphore that can be used to synchronize access.</returns>
  34.     protected SemaphoreSlim SyncRoot { get; private set; }
  35.    
  36.     /// <summary>Initializes a new instance of the <see cref="AsyncLock"/> class.</summary>
  37.     public AsyncLock()
  38.     {
  39.         SyncRoot = new SemaphoreSlim(1);
  40.     }
  41.  
  42.     /// <summary>Locks this instance.</summary>
  43.     public IDisposable Lock()
  44.     {
  45.         SyncRoot.Wait();
  46.         return this;
  47.     }
  48.     /// <summary>Locks this instance asynchronous.</summary>
  49.     /// <param name="cancellationToken">The cancellation token.</param>
  50.     public async Task<IDisposable> LockAsync(CancellationToken cancellationToken = default(CancellationToken))
  51.     {
  52.         await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false); 
  53.         return this;
  54.     }
  55.  
  56.     /// <summary>Unlocks this instance.</summary>
  57.     public IDisposable Release()
  58.     {
  59.         SyncRoot.Release();
  60.         return this;
  61.     }
  62.  
  63.     /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
  64.     public void Dispose()
  65.     {
  66.         while (SyncRoot.CurrentCount == 0)
  67.             Release();
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement