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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With