Development Tip

.NET의 스레드로부터 안전한 컬렉션

yourdevel 2020. 11. 14. 11:09
반응형

.NET의 스레드로부터 안전한 컬렉션


스레드로부터 안전한 컬렉션 (예 : Set)이 필요한 요즘 표준은 무엇입니까? 직접 동기화합니까, 아니면 본질적으로 스레드로부터 안전한 컬렉션이 있습니까?


.NET 4.0 Framework는 System.Collections.Concurrent 네임 스페이스 에 여러 스레드로부터 안전한 컬렉션을 도입했습니다 .

ConcurrentBag <T>
      스레드로부터 안전한, 정렬되지 않은 개체 컬렉션을 나타냅니다.

ConcurrentDictionary <TKey, TValue>
    여러 스레드에서 동시에 액세스 할 수있는 키-값 쌍의 스레드로부터 안전한 컬렉션을 나타냅니다.

ConcurrentQueue <T>
    스레드로부터 안전한 FIFO (선입 선출) 컬렉션을 나타냅니다.

ConcurrentStack <T>
    스레드로부터 안전한 LIFO (last in-first out) 컬렉션을 나타냅니다.


.NET Framework의 다른 컬렉션은 기본적으로 스레드로부터 안전하지 않으며 각 작업에 대해 잠 가야합니다.

lock (mySet)
{
    mySet.Add("Hello World");
}

.net 4.0 이전의 대부분의 .Net 컬렉션은 스레드로부터 안전하지 않습니다. 동기화를 처리하려면 몇 가지 작업을 직접 수행해야합니다. http://msdn.microsoft.com/en-us/library/573ths2x.aspx

기사에서 인용 :

컬렉션 클래스는 다음 방법 중 하나를 사용하여 스레드로부터 안전하게 만들 수 있습니다.

Synchronized 메서드를 사용하여 스레드로부터 안전한 래퍼를 만들고 해당 래퍼를 통해서만 컬렉션에 액세스합니다.

클래스에 Synchronized 메서드가없는 경우 클래스에서 파생되고 SyncRoot 속성을 사용하여 Synchronized 메서드를 구현합니다.

컬렉션에 액세스 할 때 SyncRoot 속성에서 C #의 lock 문 (Visual Basic의 경우 SyncLock)과 같은 잠금 메커니즘을 사용합니다.

동기화 루트 속성
잠금 문

Object thisLock = new Object();
......
lock (thisLock)
{
    // Critical code section
}

.net 4.0에서는 System.Collections.Concurrent 네임 스페이스 가 도입되었습니다.

Blocking Collection
동시 Bag
동시 큐
동시 사전
Ordable 분할 자
분할 자
분할 자 T


.NET 4는 System.Collections.Concurrent 아래에 스레드로부터 안전한 컬렉션 집합을 제공합니다.


에서 매우 유용한 클래스 외에도 System.Collections.Concurrent.Net에도 적용 할 수있는 거의 읽기가 거의없는 시나리오 (또는 빈번하지만 동시 쓰기가 아닌 경우)에서 하나의 표준 기술을 Copy-on-write라고합니다. .

고도로 동시적인 프로그램에서 바람직한 몇 가지 속성이 있습니다.

  • collection object instances themselves are immutable (i.e. thread-safe, can be safely enumerated without locking)
  • modification can take as much time as it wants, performance and concurrency of reads are not affected
  • can be implemented generically to turn any data structure that is not thread-safe into one that is

Limitation: If there are concurrent writes, modifications may have to be retried, so the more concurrent writes get, the less efficient it becomes. (That's optimistic concurrency at work)

Edit Scott Chamberlain's comment reminded me that there's another limitation: If your data structures are huge, and modifications occur often, a copy-all-on-write might be prohibitive both in terms of memory consumption and the CPU cost of copying involved.

참고URL : https://stackoverflow.com/questions/2980283/thread-safe-collections-in-net

반응형