Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<T> to BlockingCollection<T>

Tags:

c#

I'm trying to convert List<T> to BlockingCollection<T> and here's my code..

List<Job> jobs = new List<Job>
    {
        new Job() {Id=Guid.NewGuid(), Name="test1" },
        new Job() {Id=Guid.NewGuid(), Name="test2" },
        new Job() {Id=Guid.NewGuid(), Name="test3" },
    };

BlockingCollection<Job> coll = jobs as BlockingCollection<Job>;

And Job class is defined as..

public class Job
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

This type casting doesn't seem to work. Is there any easier and performance efficient way to convert List<T> to BlockingCollection<T> without looping through the list and explicitly adding each list item to the collection?

like image 688
Dinesh Avatar asked May 04 '16 02:05

Dinesh


1 Answers

BlockingCollection<T> provides a constructor which accepts an IProducerConsumerCollection<T>. You can therefore leverage an IProducerConsumerCollection<T> implementation which has an efficient IEnumerable<T> copy mechanism such as ConcurrentQueue<T>.

List<Job> jobs = new List<Job> {
    new Job { Id = Guid.NewGuid(), Name = "test1" },
    new Job { Id = Guid.NewGuid(), Name = "test2" },
    new Job { Id = Guid.NewGuid(), Name = "test3" },
};

BlockingCollection<Job> col = new BlockingCollection<Job>(new ConcurrentQueue<Job>(jobs));

This avoids the (rather significant) locking overheads associated with adding items to the collection one by one.

like image 111
Kirill Shlenskiy Avatar answered Nov 08 '22 21:11

Kirill Shlenskiy