Scenario:
Create Data Pool of numbers using Concurrent Queue.Solution:
C# ConcurrentQueue is a thread-safe collection class. It is introduced in .NET 4.0 with other concurrent collection classes. It provides a thread-safe First-In-First-Out (FIFO) data structure. ConcurrentQueue exists in System.Collections.Concurrent namespace. ConcurrentQueue is a wrapper around generic Queue class
using System.Collections.Concurrent; namespace TestProject { public class PoolNextData { private readonly Dictionary<string, ConcurrentQueue<long>> _dataPool; private int _poolLength; public PoolNextData() { _dataPool = new Dictionary<string, ConcurrentQueue<long>>(); } private long[] GetNextData(ConcurrentQueue<long> pool, string kind, int noOfRecords) { var result = new List<long>(); for (var i = 0; i < noOfRecords; i++) { long data; if (!pool.TryDequeue(out data)) { break; } result.Add(data); } //not enough available, put it back if (result.Count < noOfRecords) { FillPool(pool, kind, noOfRecords - result.Count + _poolLength); result.ForEach(pool.Enqueue); } else { Task.Factory.StartNew(() => FillPool(pool, kind, noOfRecords)); } return result.ToArray(); } private void FillPool(ConcurrentQueue<long> pool, string kind, int noOfRecords) { //Get next numbers list from DB var nos = new List<long>(); nos.ForEach(pool.Enqueue); } private ConcurrentQueue<long> GetPool(string kind) { var result = new ConcurrentQueue<long>(); _dataPool.Add(kind, result); return result; } } }
No comments:
Post a Comment