Skip to content

Instantly share code, notes, and snippets.

@markrendle
Last active May 16, 2022 14:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markrendle/0d5b8bee603c16d224af48490d135569 to your computer and use it in GitHub Desktop.
Save markrendle/0d5b8bee603c16d224af48490d135569 to your computer and use it in GitHub Desktop.
Better implementation of ChannelsQueue
public class ChannelsQueue : IJobQueue<Action>
{
private ChannelWriter<Action> _writer;
public ChannelsQueue()
{
var channel = Channel.CreateUnbounded<Action>();
var reader = channel.Reader;
_writer = channel.Writer;
Task.Factory.StartNew(async () =>
{
while (await reader.WaitToReadAsync())
{
// Fast loop around available jobs
while (reader.TryRead(out var job))
{
job.Invoke();
}
}
} , TaskCreationOptions.LongRunning);
}
public async void Enqueue(Action job)
{
_writer.TryWrite(job);
}
public void Stop()
{
_writer.Complete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment