A list with nonzero entries ends with null. Sync problem?

First of all, sorry for the headline - I could not understand what was short and clear enough.

Here's the problem: I have a list List<MyClass> list, to which I always add the newly created instances MyClass, for example list.Add(new MyClass()). I do not add elements in any other way.

However, then I iterate over the list with foreachand find that there are some null entries. That is, the following code:

foreach (MyClass entry in list)
    if (entry == null)
         throw new Exception("null entry!");

sometimes throws an exception. I must indicate what list.Add(new MyClass())is being executed from different threads working simultaneously. The only thing I can come up with for recording records nullis simultaneous access. After all, List<>it is not thread safe. Although it still seems strange to me that it ends up with empty records, it doesn’t just give no guarantees when ordering.

Can you come up with any other reason?

Also, I don't care in what order the elements are added, and I don't want the calling threads to block waiting for their elements to be added. If synchronization is really a problem, can you recommend a simple way to call the method Addasynchronously, i.e. Create a delegate to take care of this while my thread continues to work with its code? I know that I can create a delegate for Addand call BeginInvokeon it. Does this seem appropriate?

Thank.


EDIT : A simple solution based on Kevin's assumption:

public class AsynchronousList<T> : List<T> {

    private AddDelegate addDelegate;
    public delegate void AddDelegate(T item);

    public AsynchronousList() {
        addDelegate = new AddDelegate(this.AddBlocking);
    }

    public void AddAsynchronous(T item) {
        addDelegate.BeginInvoke(item, null, null);
    }

    private void AddBlocking(T item) {
        lock (this) {
            Add(item);
        }
    }
}

I only need to manage the operations Add, and I just need this for debugging (this will not be in the final product), so I just need a quick fix.

Thank you all for your answers.

+3
3

List<T> . , . , -, , ( , ).

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

, , , . , "" . , , , , , .

+8

, , . List<> .

. , -, , .

, , , List<> , , ( , Reflector Shared Source), ). , " ". , " " :

  • , .
  • < - + 1
  • [ ] =

, , Add. :

  • A: < - + 1
  • B: < - + 1
  • : [ ] =
  • B: [ ] =

null , , A, !

, List<> . , ArrayList, ; . , , , , , "" . API, , - - , , , API , .

, .

- - , , , , async, , . , , , , .

+3

.NET Framework 4, Concurrent Collections. , , . , , , , .

- Framework 2 3.5 , . Add ( - , - ?), . Adds , . Multiple-Producer-Single-Consumer, AakashM.

+1

Source: https://habr.com/ru/post/1742823/


All Articles