Lincoln Teixeira
Lincoln Teixeira

Reputation: 165

C# Collection ConcurrentBag reverse itens during concurrency update

I using a ConcurrentBag as Collection that is thread safe, to avoid conflicts when i am updating my collection in differents threads.

But i notice that sometimes the itens get inverse, my firts item goes to the last position of my collection.

I just wanna know if this may be happening due to change the collection in concurrency. If it's not possible what could may be messing up my collection?

Edit: I'm adding some sample code.

When i need to add a item i make this:

var positionToInsert = (int)incremental.MDEntryPositionNo - 1;
concurrentList.ToList().Insert(positionToInsert, myListInfoToInsert);

In some cases i need to update a position so i do like this

var foundPosition = concurrentList.ToList()
                    .FirstOrDefault(orderBook => orderBook.BookPosition == incremental.MDEntryPositionNo);

var index = concurrentList.ToList().IndexOf(foundPosition);
if (index != -1)
{
   concurrentList.ToList()[index] = infoToUpdate;
}

Thaks!

Upvotes: 1

Views: 1039

Answers (1)

Stanislav
Stanislav

Reputation: 470

Edited: Just use sorting, don't use insertion it's a slow operation.

var orderedBooks = concurrentList.OrderBy(x=>x.BookPosition).ToList();

ConcurrentBag is implemented as a linked list, and the ToList code is shown below. For each input thread, created own ThreadLocalList or reused free. The head of a linked list is always the same, and I don't understand how the order can change in this situation. However you can't guarantee that the last item added won't be in the first bucket.

Please add your sample code.

private List<T> ToList()
{
    List<T> objList = new List<T>();
    for (ConcurrentBag<T>.ThreadLocalList threadLocalList = this.m_headList; threadLocalList != null; threadLocalList = threadLocalList.m_nextList)
    {
        for (ConcurrentBag<T>.Node node = threadLocalList.m_head; node != null; node = node.m_next)
            objList.Add(node.m_value);
    }
    return objList;
}

Upvotes: 1

Related Questions