question

zipswich avatar image
0 Votes"
zipswich asked RoyLi-MSFT commented

ConcurrentQueue.First() occaionally throws "InvalidOperationException: Sequence contains no elements" when it is NOT empty



ConcurrentQueue.First()

 if (myConcurrentQueue.IsEmpty)
 {
     //do nothing
 }
 else
 {
     try
     {
         sdFirst = myConcurrentQueue.First();
     }
     catch (InvalidOperationException ex)
     {
         Debug.WriteLine("myConcurrentQueue.Count: " + myConcurrentQueue.Count);
     }
 }

The above code occasionally throws the following exception:

System.InvalidOperationException: Sequence contains no elements
Stack Trace:
at System.Linq.Enumerable.First[TSource](IEnumerable`1) + 0x43

When the exception is thrown, myConcurrentQueue.Count is well above zero (e.g., 6, 10).

Could anyone shed some light on this?

windows-uwp
· 7
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Could you reproduce this? It will be better if you could reproduce this and share the real scenario about this behavior.

0 Votes 0 ·

@RoyLi-MSFT I cannot, unfortunately. It is reported in analytics logs occasionally. I can insert any debugging code to help track down the culprit.

0 Votes 0 ·

It's hard to find out the issue because we don't know the real scenario. I don't come up with any ideas why this happens except the Queue is not correct. My suggestion is that since you've handled the exception, check the myConcurrentQueue and call the function again.



0 Votes 0 ·
Show more comments

Why ever use Linq when there are specialized methods TryDequeue and TryPeek? Are you sure that enumerator is thread safe?

0 Votes 0 ·

I do not know if the enumerator is thread safe. I thought ConcurrentQueue would take care of it.
I probably should use TryPeek. The field used to be a list before it was changed to ConcurrentQueue, but not all related code has changed accordingly.

0 Votes 0 ·

0 Answers