Skip to content

Instantly share code, notes, and snippets.

@JeffreyZhao
Created February 21, 2014 09:39
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 JeffreyZhao/9131425 to your computer and use it in GitHub Desktop.
Save JeffreyZhao/9131425 to your computer and use it in GitHub Desktop.
public class LimitConcurrencyLevelScheduler : LocalScheduler
{
private readonly ActionBlock<Action> _actionBlock;
public LimitConcurrencyLevelScheduler(int concurrencyLevel = 0, bool singleProducerConstrained = false)
{
var options = new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = concurrencyLevel <= 0 ? 1 : concurrencyLevel,
SingleProducerConstrained = singleProducerConstrained
};
_actionBlock = new ActionBlock<Action>(a => a(), options);
}
public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (dueTime.Ticks > 0)
throw new NotSupportedException();
var m = new SingleAssignmentDisposable();
_actionBlock.Post(() =>
{
if (!m.IsDisposed)
m.Disposable = action(this, state);
});
return m;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment