Last active
May 15, 2016 11:46
-
-
Save dupdob/edbee53c0bf382a6e5e9 to your computer and use it in GitHub Desktop.
Sequencer 2.0 alpha
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 | |
{ | |
public class Sequencer | |
{ | |
private Queue<Action> _pendingTasks = new Queue<Action>(); | |
private bool _isRunning; | |
private readonly object _lock = new Object(); | |
public void Dispatch(Action action) | |
{ | |
lock(_lock) { | |
// we need to store | |
_pendingTasks.Enqueue(action); | |
} | |
// here we queue a call to our own logic | |
ThreadPool.QueueUserWorkItem( (x)=> Run((Action) x), action ); | |
} | |
// run when the pool has available cpu time for us. | |
private void Run(Action action) | |
{ | |
lock(_lock) { | |
if (_isRunning) { | |
// we need to stop | |
return; | |
} | |
// ok, we can run | |
_isRunning = true; | |
} | |
while (true) { | |
// execute the next action | |
action (); | |
// we check if others are available | |
lock (_lock) { | |
if (_pendingTasks.Count == 0) { | |
_isRunning = false; | |
return; | |
} | |
// pop the next task | |
action = _pendingTasks.Dequeue(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does sequencer is trying to address the producer-consumer problem?
https://gist.github.com/valerysntx/1cb73ae17e71b8123b1cd4d4dd18c9d8#file-producerconsumerqueue-cs