0

How can channel input be handled in a prioritized fashion? Is there anything equivalent to Scala's "reactWithin(0) { ... case TIMEOUT }" construct?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
anthony
  • 40,424
  • 5
  • 55
  • 128

1 Answers1

0

I wrote a Subscription class that delivers prioritized messages on a set interval. It's not an ideal general case way to consume prioritized messages, but I'll post it for posterity. I think a custom RequestReplyChannel would be a better option for certain other cases. Implementation of PriorityQueue is left as an exercise to the reader.

class PrioritySubscriber<T> : BaseSubscription<T>
{
    private readonly PriorityQueue<T> queue;
    private readonly IScheduler scheduler;
    private readonly Action<T> receive;
    private readonly int interval;

    private readonly object sync = new object();
    private ITimerControl next = null;

    public PrioritySubscriber(IComparer<T> comparer, IScheduler scheduler,
        Action<T> receive, int interval)
    {
        this.queue = new PriorityQueue<T>(comparer);
        this.scheduler = scheduler;
        this.receive = receive;
        this.interval = interval;
    }

    protected override void OnMessageOnProducerThread(T msg)
    {
        lock (this.sync)
        {
            this.queue.Enqueue(msg);

            if (this.next == null)
            {
                this.next =
                    this.scheduler.Schedule(this.Receive, this.interval);
            }
        }
    }

    private void Receive()
    {
        T msg;

        lock (this.sync)
        {
            msg = this.queue.Dequeue();

            if (this.queue.Count > 0)
            {
                this.next =
                    this.scheduler.Schedule(this.Receive, this.interval);
            }
        }

        this.receive(msg);
    }
}
anthony
  • 40,424
  • 5
  • 55
  • 128
  • Instead of writing your own you could consider using Wintellect's Power Collections for .NET (OrderedBag), you can find these via CodePlex. – Rick Oct 22 '09 at 12:12