Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Main()
- {
- var alock = new AsyncLock();
- int numberOfTasks = 100000;
- int counterLocked = 0;
- int counterAtomicBegin = 0;
- int counterAtomicEnd = 0;
- Task[] tasks = new Task[numberOfTasks];
- for (int i = 0; i < numberOfTasks; i++)
- {
- tasks[i] = Task.Run<Task>(async () =>
- {
- Interlocked.Increment(ref counterAtomicBegin);
- using (await alock.LockAsync().ConfigureAwait(false))
- {
- counterLocked += 1;
- }
- Interlocked.Increment(ref counterAtomicEnd);
- });
- }
- bool result = Task.WaitAll(tasks, 10000);
- String.Format("counterLocked={0}; counterAtomicBegin={1}",
- counterLocked, counterAtomicBegin).Dump();
- }
- /// <summary>Wrapper for locking in an asynchronous way.</summary>
- public class AsyncLock : IDisposable
- {
- /// <summary>Gets a semaphore that can be used to synchronize access.</summary>
- /// <returns>A semaphore that can be used to synchronize access.</returns>
- protected SemaphoreSlim SyncRoot { get; private set; }
- /// <summary>Initializes a new instance of the <see cref="AsyncLock"/> class.</summary>
- public AsyncLock()
- {
- SyncRoot = new SemaphoreSlim(1);
- }
- /// <summary>Locks this instance.</summary>
- public IDisposable Lock()
- {
- SyncRoot.Wait();
- return this;
- }
- /// <summary>Locks this instance asynchronous.</summary>
- /// <param name="cancellationToken">The cancellation token.</param>
- public async Task<IDisposable> LockAsync(CancellationToken cancellationToken = default(CancellationToken))
- {
- await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false);
- return this;
- }
- /// <summary>Unlocks this instance.</summary>
- public IDisposable Release()
- {
- SyncRoot.Release();
- return this;
- }
- /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
- public void Dispose()
- {
- while (SyncRoot.CurrentCount == 0)
- Release();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement