Dequeue sets the head.Value to its default. When TryPeek is interrupted in the process of retrieving the value some times Dequeue sets the value to its default. TryPeek now checks the head has not been changed before returning the value.
public bool TryPeek (out T result)
{
- Node first = head.Next;
+ result = default (T);
+ bool update = true;
+
+ while (update)
+ {
+ Node oldHead = head;
+ Node oldNext = oldHead.Next;
- if (first == null) {
- result = default (T);
- return false;
- }
+ if (oldNext == null) {
+ result = default (T);
+ return false;
+ }
- result = first.Value;
+ result = oldNext.Value;
+
+ //check if head has been updated
+ update = head != oldHead;
+ }
return true;
}