سؤال

وكيف يمكن توجيه يتم التعامل معها المدخلات بطريقة ذي الأولوية؟ هل هناك أي شيء يعادل ل"reactWithin(0) { ... case TIMEOUT }" سكالا في بناء؟

هل كانت مفيدة؟

المحلول

وكتبت فئة الاشتراك من شأنها أن توفر الرسائل ذات الأولوية على فترة زمنية محددة. انها ليست مثالية وسيلة الحالة العامة للاستهلاك الرسائل ذات الأولوية، ولكن أنا ما بعد ذلك للأجيال القادمة. أعتقد أن RequestReplyChannel مخصصة يكون خيارا أفضل بالنسبة لبعض الحالات الأخرى. تبقى تنفيذ PriorityQueue باعتبارها ممارسة للقارئ.

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);
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top