[Fix] Bugzilla #18182 - ConcurrentQueue<T>.TryPeek() is not thread safe
authorCraig Minihan <v-craig.minihan@exony.com>
Wed, 5 Mar 2014 15:24:14 +0000 (07:24 -0800)
committerCraig Minihan <v-craig.minihan@exony.com>
Sat, 15 Mar 2014 20:50:51 +0000 (13:50 -0700)
- in the previous version the IsEmpty could be false, but by time we get
  to head.Next.Value we get an exception since Value is now null
- passes existing test cases, although these are not definitive since
  they don't show threading issue
- would need to adapt System.Threading.Tasks.ParallelTestHelper to allow
  TryPeek() to be called during Enqueue/Dequeue operations to truly
  test this change out

mcs/class/corlib/System.Collections.Concurrent/ConcurrentQueue.cs

index f4cdcc99e6d4c51476557fcd59e249b72bdfef88..f6387fa133db434200b1fa4497b95bc3a81bdf73 100644 (file)
@@ -128,14 +128,15 @@ namespace System.Collections.Concurrent
                }
                
                public bool TryPeek (out T result)
-               {
-                       if (IsEmpty) {
+               {               
+                       Node first = head.Next; 
+                       
+                       if (IsEmpty || first == null) {
                                result = default (T);
                                return false;
                        }
-                       
-                       Node first = head.Next;
-                       result = first.Value;
+                                                       
+                       result = first.Value;                   
                        return true;
                }