An efficient way of starting an arbitrary number of consumer threads?

I have a Producer/Consumer implementation where the number of consumers is configurable (this is a form of configurable throttling). The producer and consumer are kicked off like this:

var cts = new CancellationTokenSource();
var processCancelToken = cts.Token;

Task.Run(() => Parallel.Invoke(new ParallelOptions() { CancellationToken = processCancelToken }
                               , producer
                               , consumer
                               )
               , processCancelToken);

The producer action is quite simple and just populates a BlockingCollection with objects that are derived from System.Threading.Tasks.Task (yes it is possible!). Here is a simplified example:

var pollingInterval = 30000;

var producer = new Action(() =>
{
    Random rnd = new Random(DateTime.Now.Second);
    while (!processCancelToken.IsCancellationRequested)
    {
        for (int ii = 0; ii < 10; ii++)
        {
            var r = rnd.Next(2, 15);
            _mainQueue.Add(new Task(() =>
            {
                //this is a dummy task for illustrative purposes
                Console.WriteLine("        Queued task starting, set to sleep {0} seconds, ID: {1}", r, Thread.CurrentThread.ManagedThreadId); 
                Thread.Sleep(r*1000);
            }));
            Console.WriteLine("    Producer has added task to queue");

        }
        System.Threading.Thread.Sleep(pollingInterval);
    }
    Console.WriteLine("Exiting producer");
}

For this example it creates an anonymous task that sleeps for a random number of seconds between 2 and 15. In the real code this producer polls the database, extracts data entities representing work items, then transforms those into executable tasks that are added to the collection.

I then have a consumer task that uses a Parallel.For() to start n instances of an anonymous action which then dequeues a task from the collection, then starts and waits on the task, then repeats:

var numberConsumerThreads = 3;

var consumer = new Action(() =>
{
    Parallel.For(0, numberConsumerThreads, (x) =>
    {
        //this action should continue to dequeue work items until it is cancelled
        while (!processCancelToken.IsCancellationRequested)
        {
            var dequeuedTask = _mainQueue.Take(processCancelToken);
            Console.WriteLine("   Consumer #{0} has taken task from the queue", Thread.CurrentThread.ManagedThreadId);

            dequeuedTask.Start();
            while (!processCancelToken.IsCancellationRequested)
            {
                if (dequeuedTask.Wait(500))
                    break;
                Console.WriteLine("   Consumer #{0} task wait elapsed", Thread.CurrentThread.ManagedThreadId);
            }
        }
        Console.WriteLine("Exiting consumer #{0}", Thread.CurrentThread.ManagedThreadId);
    });
}

The question: is this an efficient way to start and operate an arbitrary number of consumers? Or is there a more efficient way of using PLINQ from within the main consumer action that both continues to execute queued tasks, blocks while there isn’t any, and can still be cancelled using processCancelToken?

(Note: processCancelToken is operated separately to cancel tokens contained within the queued tasks – they are independently cancelable. This all runs within a Windows service and processCancelToken is used to cancel everything if the service is stopped).

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật