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

Commit

Permalink
optimize
Browse files Browse the repository at this point in the history
  • Loading branch information
justcoding121 committed Apr 13, 2018
1 parent 521fb1c commit c5d83e7
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions EventHook/Helpers/AsyncQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
namespace EventHook.Helpers
{
/// <summary>
/// A concurrent queue facilitating async dequeue
/// Since our consumer is always single threaded no locking is needed
/// A concurrent queue facilitating async dequeue with minimal locking
/// Assumes single/multi-threaded producer and a single-threaded consumer
/// </summary>
/// <typeparam name="T"></typeparam>
internal class AsyncQueue<T>
Expand All @@ -25,10 +25,10 @@ internal AsyncQueue(CancellationToken taskCancellationToken)
/// <summary>
/// Keeps any pending Dequeue task to wake up once data arrives
/// </summary>
TaskCompletionSource<T> dequeueTask;
TaskCompletionSource<bool> dequeueTask;

/// <summary>
/// Assumes a single threaded producer!
/// Supports multi-threaded producers
/// </summary>
/// <param name="value"></param>
internal void Enqueue(T value)
Expand All @@ -39,15 +39,12 @@ internal void Enqueue(T value)
if (dequeueTask != null
&& !dequeueTask.Task.IsCompleted)
{
T result;
queue.TryDequeue(out result);
dequeueTask.SetResult(result);
dequeueTask.SetResult(true);
}

}

/// <summary>
/// Assumes a single threaded consumer!
/// Assumes a single-threaded consumer!
/// </summary>
/// <returns></returns>
internal async Task<T> DequeueAsync()
Expand All @@ -60,11 +57,12 @@ internal async Task<T> DequeueAsync()
return result;
}

dequeueTask = new TaskCompletionSource<T>();
dequeueTask = new TaskCompletionSource<bool>();
taskCancellationToken.Register(() => dequeueTask.TrySetCanceled());
result = await dequeueTask.Task;
await dequeueTask.Task;
dequeueTask = null;

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

Expand Down

0 comments on commit c5d83e7

Please sign in to comment.