classic producer consumer pattern using blockingcollection and tasks .net 4 TPL

前端 未结 3 1845
醉酒成梦
醉酒成梦 2020-12-05 07:49

Please see below pseudo code

//Single or multiple Producers produce using below method
    void Produce(object itemToQueue)
    {
        concurrentQueue.enq         


        
3条回答
  •  执念已碎
    2020-12-05 08:12

    I've used a pattern before that creates a sort of 'on-demand' queue consumer (based on consuming from a ConcurrentQueue):

            private void FireAndForget(Action fire)
            {
                _firedEvents.Enqueue(fire);
                lock (_taskLock)
                {
                    if (_launcherTask == null)
                    {
                        _launcherTask = new Task(LaunchEvents);
                        _launcherTask.ContinueWith(EventsComplete);
                        _launcherTask.Start();
                    }
                }
            }
    
            private void LaunchEvents()
            {
                Action nextEvent;
    
                while (_firedEvents.TryDequeue(out nextEvent))
                {
                    if (_synchronized)
                    {
                        var syncEvent = nextEvent;
                        _mediator._syncContext.Send(state => syncEvent(), null);
                    }
                    else
                    {
                        nextEvent();                        
                    }
    
                    lock (_taskLock)
                    {
                        if (_firedEvents.Count == 0)
                        {
                            _launcherTask = null;
                            break;
                        }
                    }
                }
            }
    
            private void EventsComplete(Task task)
            {
                if (task.IsFaulted && task.Exception != null)
                {
                     // Do something with task Exception here
                }
            }
    

提交回复
热议问题