Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
ThreadSafeQueue.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 
4 using System.Collections.Generic;
5 
6 namespace SiliconStudio.Paradox.Audio
7 {
8  /// <summary>
9  /// Thread safe queue.
10  /// </summary>
11  /// <remarks>Fields <see cref="InternalQueue"/> and <see cref="InternalLock"/> can be used to perform specific optimizations.
12  /// In this case it is the responsibility of the user to ensure the proper use of the Queue.</remarks>
13  /// <typeparam name="T"></typeparam>
14  internal class ThreadSafeQueue<T>
15  {
16  private readonly List<T> cachedDequeueList = new List<T>();
17 
18  private readonly object internalLock = new object();
19  public object InternalLock
20  {
21  get { return internalLock; }
22  }
23 
24  private readonly Queue<T> internalQueue = new Queue<T>();
25  public Queue<T> InternalQueue
26  {
27  get { return internalQueue; }
28  }
29 
30  public int Count
31  {
32  get
33  {
34  lock (InternalLock)
35  {
36  return internalQueue.Count;
37  }
38  }
39  }
40 
41  public void Enqueue(T item)
42  {
43  lock (InternalLock)
44  {
45  internalQueue.Enqueue(item);
46  }
47  }
48 
49  public bool TryDequeue(out T result)
50  {
51  bool ret;
52 
53  result = default(T);
54 
55  lock (InternalLock)
56  {
57  ret = internalQueue.Count > 0;
58  if (ret)
59  result = internalQueue.Dequeue();
60  }
61 
62  return ret;
63  }
64 
65  public List<T> DequeueAsList()
66  {
67  lock (InternalLock)
68  {
69  cachedDequeueList.Clear();
70 
71  while (internalQueue.Count > 0)
72  cachedDequeueList.Add(internalQueue.Dequeue());
73 
74  return cachedDequeueList;
75  }
76  }
77  }
78 }