-
-
Save freeman/011c729110bdef88a516 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
using System; | |
using System.Collections.Generic; | |
using System.Threading; | |
namespace Sequencer | |
{ | |
using System.Collections.Concurrent; | |
public class Sequencer | |
{ | |
private readonly ConcurrentQueue<Action> _pendingTasks = new ConcurrentQueue<Action>(); | |
private readonly object _running = new Object(); | |
public void Dispatch(Action action) | |
{ | |
// Queue the task | |
_pendingTasks.Enqueue(action); | |
// Schedule a processing run (may be a noop) | |
ThreadPool.QueueUserWorkItem( x=> Run()); | |
} | |
// run when the pool has available cpu time for us. | |
private void Run() | |
{ | |
if (Monitor.TryEnter(_running)) | |
{ | |
try | |
{ | |
Action taskToRun; | |
while (_pendingTasks.TryDequeue(out taskToRun)) | |
{ | |
taskToRun(); | |
} | |
} | |
finally | |
{ | |
Monitor.Exit(_running); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment