Skip to content
This repository has been archived by the owner on Apr 21, 2021. It is now read-only.

Commit

Permalink
Use semaphore slim async lock on dequeue task object
Browse files Browse the repository at this point in the history
  • Loading branch information
justcoding121 committed Apr 24, 2018
1 parent 4e5b1ff commit eef2b97
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions EventHook/Helpers/AsyncConcurrentQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ internal class AsyncConcurrentQueue<T>
private readonly ConcurrentQueue<T> queue = new ConcurrentQueue<T>();

/// <summary>
/// Keeps any pending Dequeue task to wake up once data arrives
/// Wake up any pending dequeue task
/// </summary>
private TaskCompletionSource<bool> dequeueTask;

private SemaphoreSlim @dequeueTaskLock = new SemaphoreSlim(1);
private CancellationToken taskCancellationToken;

internal AsyncConcurrentQueue(CancellationToken taskCancellationToken)
Expand All @@ -36,8 +36,11 @@ internal void Enqueue(T value)
{
queue.Enqueue(value);

//wake up the dequeue task with result
dequeueTask?.TrySetResult(true);
//signal
dequeueTaskLock.Wait();
dequeueTask.TrySetResult(true);
dequeueTaskLock.Release();

}

/// <summary>
Expand All @@ -54,10 +57,13 @@ internal async Task<T> DequeueAsync()
return result;
}

await dequeueTaskLock.WaitAsync();
dequeueTask = new TaskCompletionSource<bool>();
dequeueTaskLock.Release();

taskCancellationToken.Register(() => dequeueTask.TrySetCanceled());
await dequeueTask.Task;

queue.TryDequeue(out result);
return result;
}
Expand Down

0 comments on commit eef2b97

Please sign in to comment.