I'm using the ConcurrentDictionary and ConcurrentQueue classes from .NET 4 in the following code.
Is this code thread-safe? If not, how can I make it thread-safe?
public class Page
{
public string Name {get; set; }
}
public class PageQueue
{
private ConcurrentDictionary<int, ConcurrentQueue<Page>> pages =
new ConcurrentDictionary<int, ConcurrentQueue<Page>>();
public void Add(int id, Page page)
{
if (!this.pages.ContainsKey(id))
this.pages[id] = new ConcurrentQueue<Page>();
this.pages[id].Enqueue(page);
}
public Page GetAndRemove(int id)
{
Page lp = null;
if(this.pages.ContainsKey(id))
this.pages[id].TryDequeue(out lp);
return lp;
}
}
Demo:
public class Demo
{
public void RunAll()
{
for (int i = 0; i < 10; i++)
Task.Factory.StartNew(() => Run());
}
public void Run()
{
PageQueue pq = new PageQueue();
pq.Add(1, new Page());
pq.GetAndRemove(1);
}
}