简体   繁体   中英

how to remove the exception, System.InvalidOperationException?

code is given below

Queue<int> queXpTrackerX = new Queue<int>(10);
Queue<int> queXpTrackerY = new Queue<int>(10);       

if (iCounterForXpTrack < 10)
{
    queXpTrackerX.Enqueue(X);
    queXpTrackerY.Enqueue(Y);
    iCounterForXpTrack++;
}//End IF
else
{
    queXpTrackerX.Dequeue();
    queXpTrackerY.Dequeue();
    queXpTrackerX.Enqueue(X);
    queXpTrackerY.Enqueue(Y);
}//End else

for (int indexXp = 0; indexXp < iCounterForXpTrack; indexXp++)
{
    gXpTracker.DrawEllipse(Pens.Cyan, queXpTrackerX.ElementAt(indexXp) , queXpTrackerY.ElementAt(indexXp), 5, 5);
}//end for

I suspect that the most likely cause for you InvalidOperationException is trying to Dequeue from a queue when it is empty. Did you have the exception message? Is it 'Queue empty.'?

This can happen if your iCounterForXpTrack becomes out of sync with the number of elements in the queue. It would be better to just ask the queue directly to avoid this possible error:

    if (queXpTrackerX.Count < 10)
    {
        queXpTrackerX.Enqueue(X);
        queXpTrackerY.Enqueue(Y);
    }
    else
    {
        queXpTrackerX.Dequeue();
        queXpTrackerY.Dequeue();
        queXpTrackerX.Enqueue(X);
        queXpTrackerY.Enqueue(Y);
    }

A possible reason that your code fails is if you initialized iCounterForXpTrack to 10 thinking that new Queue<int>(10) creates a queue that starts with 10 elements. This is not the case. The queue is initially empty. Providing the capacity to the queue constructor is just a performance optimization and is not strictly needed.

Another issue with your code: instead of having two queues, one for x and one for y, you should use some sort of Point class and a Queue<Point> . This simplifies the code and eliminates possible errors from the two queues becoming out of sync.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM