Suppose I have a List<T> that simultaneously reads one thread and writes another one to it. In this case, what would be more correct and faster to use: volatile or ConcurrentBag?

  • 2
    On volatile by Eric Lippert - Vladislav Khapin

1 answer 1

You can talk about speed only when you have implemented functionality, and profiling shows that data access is a bottleneck. So let's deal with the correctness.

Let's start with the fact that we cannot apply volatile to the list - volatile -fields can only be of elementary types. Even if it could be applied, what's the point in synchronizing access to the container link? Racing is according to the data inside the container.

ConcurrentBag is a smarter choice. But this is only if the data is really only added in one of the streams, and not modified by it. Depending on your exact task, you may need a ConcurrentBag (if order is not important) or a ConcurrentQueue (if important).

If you need access by index, or data modification in the writing stream (for example: collection[i]++ ), you should not look for a benefit of a few microseconds, it is simpler and safer to use a normal lock .

  • Will winnings use ReadWriterLockSlim instead of lock? Or, again, do not bathe for a couple of ms? - D .Stark
  • I’ll clarify that I have 2 threads and both are actively writing and reading. (I wrote a little wrong in the question) - D .Stark
  • one
    @ D.Stark: No, it won’t. A win could be, if you have several readers - then they can simultaneously read under the read-lock. In a situation where the reader is one, on the contrary, it turns out a loss: lock is still cheaper. - VladD
  • @ D.Stark: As an optimization, you can (later) think about blocking with chunks, for example. But it depends a lot on how exactly the data “moves” around you. - VladD
  • Good. Thank. We stop at lock. - D .Stark