简体   繁体   中英

c# ArgumentOutOfRangeException

I Have this piece of code:

    private List<...> LayPrices;
    public Decimal BestLayOdds
    {
        get
        {
            if (LayPrices.Count > 0)
            {
                return LayPrices[0].dOdds;
            }
            return 1000.0M;   
        }
    }

The Problem is that sometimes the List has items, but it does not enter inside the 'if' statement.

Check the images below of a debug session:

在此输入图像描述

How is that even possible?

But if I force it to return the first item, on the last return statement, I get an ArgumentOutOfRangeException even though the list has elements. Check the nest image:

在此输入图像描述

Is there any problem with my code or it is just a stupid bug?

Update:

The LayPrices List is only instantiated on the class Constructor: LayPrices = new List<PriceStruct>(); .

It is only getting filled with items on one method, whith the following code:

    LayPrices.Clear();
    foreach (PriceSize priceSize in exchangePrices.availableToLay)
    {
          PriceStruct lay = new PriceStruct();
          lay.dOdds = (Decimal)priceSize.price;
          lay.dAmount = (Decimal)priceSize.size;

          LayPrices.Add(lay);
   }

Concurrency issues and threading were my first clue, so I did put a lock(LayPrices) and the problem still persisted:

锁

So I think it is not a concurrency issue.

Put Debug.Assert(LayPrices.Count > 0) in the getter before the if statement and you'll see that the List is in fact empty.

The only reasonable explanation is that you are populating the list either in some other thread and you have a race condition or in a property getter that only gets fired by the debugger (you could also be populating the list in a catch clause up the callstack but I imagine you would have figured that out by yourself)

In order to get a better answer please include all code that populates your list. No only the code you think should run, but all the properties, constructors or methods that add or remove items from the list.

I found the problem. It was indeed concurrency issues, even though I don't use threads explicitly, I use events and I thought event handling was synchronized (It is synchronized right?).

If I add locks everywhere I read or add to the list, the problem disappears.

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