A
A
azaznioo2018-04-22 17:02:39
ASP.NET
azaznioo, 2018-04-22 17:02:39

Questions about the thread safety of collections and objects?

1. Multiple threads need to traverse the collection to compare values. The filling of the collection will have to occur before the read operation by streams. Is it required to do this at the time of reading to make a lock lock for a regular list List? How can this problem be solved without using lock and what collection is suitable for this?
2. There is a BlockingCollection in the Concurrent space. Is it used for safe adding and reading with built-in blocking?
3. When it is required to read the property of an object from a set of streams of a reference type or an elementary one, is it necessary to make locks? And whether it is necessary to do it in case of reading by streams of a field?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
w1ld, 2018-04-26
@azaznioo

1. Well, `List` is not thread safe . To avoid Kernel-mode constructs (`lock` etc.), you can try the thread-safe ConcurrentQueue or ConcurrentStack in System.Collections.Concurrent , if filling before reading (and not in time). Fill, call GetEnumerable , which makes a snapshot of the collection, compare. Reading must occur without blocking.
2. BlockingCollection for the producer-consumer problem when reading and writing at the same time. I understand that this is not the issue.
3. If you do not change, then you do not need to block. Regardless of reference or value type. (Of course, it’s better if you change it through the stack. Then a copy for each thread has its own.)
On the topic, you can read Richter, CLR via C#, Chapter 10, Asynchronous Synchronization and The Concurrent Collection Classes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question