Created
May 23, 2014 02:51
-
-
Save Acapla/ba2477953b0dd635c862 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Queue<T> | |
{ | |
private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>(); | |
private long _count = 0; | |
private readonly Action<T> _action = null; | |
public Queue(Action<T> action) | |
{ | |
_action = action; | |
} | |
public void EnqueueAsync(T item) | |
{ | |
var count = Interlocked.Increment(ref _count); | |
_queue.Enqueue(item); | |
if (count == 1) | |
{ | |
Task.Run(() => Dequeue()); | |
} | |
} | |
private async void Dequeue() | |
{ | |
while (true) | |
{ | |
T item; | |
if (_queue.TryDequeue(out item)) | |
{ | |
_action(item); | |
var count = Interlocked.Decrement(ref _count); | |
if (count == 0) | |
{ | |
return; | |
} | |
} | |
else | |
{ | |
await Task.Yield(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment