ConcurrentBag<T> 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
스레드로부터 안전하고 순서가 지정되지 않은 개체 컬렉션을 나타냅니다.
generic <typename T>
public ref class ConcurrentBag : System::Collections::Concurrent::IProducerConsumerCollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IReadOnlyCollection<T>, System::Collections::ICollection
generic <typename T>
public ref class ConcurrentBag : System::Collections::Concurrent::IProducerConsumerCollection<T>, System::Collections::Generic::IEnumerable<T>
generic <typename T>
public ref class ConcurrentBag : System::Collections::Concurrent::IProducerConsumerCollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IReadOnlyCollection<T>
generic <typename T>
public ref class ConcurrentBag : System::Collections::Concurrent::IProducerConsumerCollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::ICollection
public class ConcurrentBag<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class ConcurrentBag<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class ConcurrentBag<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>
public class ConcurrentBag<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection
public class ConcurrentBag<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>
type ConcurrentBag<'T> = class
interface IProducerConsumerCollection<'T>
interface seq<'T>
interface IEnumerable
interface ICollection
interface IReadOnlyCollection<'T>
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type ConcurrentBag<'T> = class
interface IProducerConsumerCollection<'T>
interface seq<'T>
interface ICollection
interface IEnumerable
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type ConcurrentBag<'T> = class
interface IProducerConsumerCollection<'T>
interface seq<'T>
interface IEnumerable
interface ICollection
interface IReadOnlyCollection<'T>
type ConcurrentBag<'T> = class
interface IProducerConsumerCollection<'T>
interface seq<'T>
interface ICollection
interface IEnumerable
Public Class ConcurrentBag(Of T)
Implements ICollection, IEnumerable(Of T), IProducerConsumerCollection(Of T), IReadOnlyCollection(Of T)
Public Class ConcurrentBag(Of T)
Implements IEnumerable(Of T), IProducerConsumerCollection(Of T)
Public Class ConcurrentBag(Of T)
Implements IEnumerable(Of T), IProducerConsumerCollection(Of T), IReadOnlyCollection(Of T)
Public Class ConcurrentBag(Of T)
Implements ICollection, IEnumerable(Of T), IProducerConsumerCollection(Of T)
형식 매개 변수
- T
컬렉션에 저장할 요소의 형식입니다.
- 상속
-
ConcurrentBag<T>
- 특성
- 구현
예제
다음 예제에서는 다음에서 항목을 추가하고 제거하는 방법을 보여줍니다.ConcurrentBag<T>
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
class ConcurrentBagDemo
{
// Demonstrates:
// ConcurrentBag<T>.Add()
// ConcurrentBag<T>.IsEmpty
// ConcurrentBag<T>.TryTake()
// ConcurrentBag<T>.TryPeek()
static void Main()
{
// Add to ConcurrentBag concurrently
ConcurrentBag<int> cb = new ConcurrentBag<int>();
List<Task> bagAddTasks = new List<Task>();
for (int i = 0; i < 500; i++)
{
var numberToAdd = i;
bagAddTasks.Add(Task.Run(() => cb.Add(numberToAdd)));
}
// Wait for all tasks to complete
Task.WaitAll(bagAddTasks.ToArray());
// Consume the items in the bag
List<Task> bagConsumeTasks = new List<Task>();
int itemsInBag = 0;
while (!cb.IsEmpty)
{
bagConsumeTasks.Add(Task.Run(() =>
{
int item;
if (cb.TryTake(out item))
{
Console.WriteLine(item);
Interlocked.Increment(ref itemsInBag);
}
}));
}
Task.WaitAll(bagConsumeTasks.ToArray());
Console.WriteLine($"There were {itemsInBag} items in the bag");
// Checks the bag for an item
// The bag should be empty and this should not print anything
int unexpectedItem;
if (cb.TryPeek(out unexpectedItem))
Console.WriteLine("Found an item in the bag when it should be empty");
}
}
module ConcurrentBagDemo
open System.Collections.Concurrent
open System.Threading.Tasks
open System.Threading
// Demonstrates:
// ConcurrentBag<T>.Add()
// ConcurrentBag<T>.IsEmpty
// ConcurrentBag<T>.TryTake()
// ConcurrentBag<T>.TryPeek()
// Add to ConcurrentBag concurrently
let cb = ConcurrentBag<int>()
let bagAddTasks =
[| for i = 0 to 499 do
let numberToAdd = i
task { cb.Add numberToAdd } :> Task |]
// Wait for all tasks to complete
Task.WaitAll bagAddTasks
// Consume the items in the bag
let mutable itemsInBag = 0
let bagConsumeTasks =
[| while not cb.IsEmpty do
task {
let mutable item = 0
if cb.TryTake &item then
printfn $"{item}"
Interlocked.Increment &itemsInBag |> ignore
}
:> Task |]
Task.WaitAll bagConsumeTasks
printfn $"There were {itemsInBag} items in the bag"
// Checks the bag for an item
// The bag should be empty and this should not print anything
let mutable unexpectedItem = 0
if cb.TryPeek &unexpectedItem then
printfn "Found an item in the bag when it should be empty"
Imports System.Collections.Concurrent
Module ConcurrentBagDemo
' Demonstrates:
' ConcurrentBag<T>.Add()
' ConcurrentBag<T>.IsEmpty
' ConcurrentBag<T>.TryTake()
' ConcurrentBag<T>.TryPeek()
Sub Main()
' Add to ConcurrentBag concurrently
Dim cb As New ConcurrentBag(Of Integer)()
Dim bagAddTasks As New List(Of Task)()
For i = 1 To 500
Dim numberToAdd As Integer = i
bagAddTasks.Add(Task.Run(Sub() cb.Add(numberToAdd)))
Next
' Wait for all tasks to complete
Task.WaitAll(bagAddTasks.ToArray())
' Consume the items in the bag
Dim bagConsumeTasks As New List(Of Task)()
Dim itemsInBag As Integer = 0
While Not cb.IsEmpty
bagConsumeTasks.Add(Task.Run(Sub()
Dim item As Integer
If cb.TryTake(item) Then
Console.WriteLine(item)
itemsInBag = itemsInBag + 1
End If
End Sub))
End While
Task.WaitAll(bagConsumeTasks.ToArray())
Console.WriteLine($"There were {itemsInBag} items in the bag")
' Checks the bag for an item
' The bag should be empty and this should not print anything
Dim unexpectedItem As Integer
If cb.TryPeek(unexpectedItem) Then
Console.WriteLine("Found an item in the bag when it should be empty")
End If
End Sub
End Module
설명
가방은 주문이 중요하지 않을 때 개체를 저장하는 데 유용하며 집합과 달리 가방은 중복을 지원합니다. ConcurrentBag<T> 는 동일한 스레드가 백에 저장된 데이터를 생성하고 사용하는 시나리오에 최적화된 스레드로부터 안전한 모음 구현입니다.
ConcurrentBag<T> 는 null 참조 형식에 유효한 값으로 허용됩니다.
자세한 내용은 .NET 블로그가 있는 병렬 프로그래밍에서 FAQ: 모든 새 동시 컬렉션이 잠금 해제되어 있나요? 항목을 참조하세요.
생성자
| Name | Description |
|---|---|
| ConcurrentBag<T>() |
ConcurrentBag<T> 클래스의 새 인스턴스를 초기화합니다. |
| ConcurrentBag<T>(IEnumerable<T>) |
지정된 컬렉션에서 복사한 요소를 포함하는 클래스의 ConcurrentBag<T> 새 인스턴스를 초기화합니다. |
속성
| Name | Description |
|---|---|
| Count |
에 포함된 ConcurrentBag<T>요소 수를 가져옵니다. |
| IsEmpty |
비어 있는지 여부를 ConcurrentBag<T> 나타내는 값을 가져옵니다. |
메서드
| Name | Description |
|---|---|
| Add(T) |
에 개체를 ConcurrentBag<T>추가합니다. |
| Clear() |
에서 모든 값을 ConcurrentBag<T>제거합니다. |
| CopyTo(T[], Int32) |
지정된 배열 인덱스에서 ConcurrentBag<T> 시작하여 요소를 기존 1차원 Array으로 복사합니다. |
| Equals(Object) |
지정한 개체와 현재 개체가 같은지 여부를 확인합니다. (다음에서 상속됨 Object) |
| GetEnumerator() |
를 반복하는 열거자를 반환합니다 ConcurrentBag<T>. |
| GetHashCode() |
기본 해시 함수로 작동합니다. (다음에서 상속됨 Object) |
| GetType() |
현재 인스턴스의 Type 가져옵니다. (다음에서 상속됨 Object) |
| MemberwiseClone() |
현재 Object단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
| ToArray() |
요소를 새 배열에 복사합니다 ConcurrentBag<T> . |
| ToString() |
현재 개체를 나타내는 문자열을 반환합니다. (다음에서 상속됨 Object) |
| TryPeek(T) |
개체를 제거하지 않고 개체를 ConcurrentBag<T> 반환하려고 시도합니다. |
| TryTake(T) |
에서 개체를 제거하고 반환하려고 시도합니다 ConcurrentBag<T>. |
명시적 인터페이스 구현
| Name | Description |
|---|---|
| ICollection.CopyTo(Array, Int32) |
특정 ICollection 인덱스에서 시작하여 Array 요소를 Array복사합니다. |
| ICollection.IsSynchronized |
액세스 ICollection 가 SyncRoot와 동기화되는지 여부를 나타내는 값을 가져옵니다. |
| ICollection.SyncRoot |
ICollection대한 액세스를 동기화하는 데 사용할 수 있는 개체를 가져옵니다. 이 속성은 지원되지 않습니다. |
| IEnumerable.GetEnumerator() |
를 반복하는 열거자를 반환합니다 ConcurrentBag<T>. |
| IProducerConsumerCollection<T>.TryAdd(T) |
에 개체를 추가하려고 시도합니다 ConcurrentBag<T>. |
확장명 메서드
적용 대상
스레드 보안
모든 공용 및 보호된 멤버 ConcurrentBag<T> 는 스레드로부터 안전하며 여러 스레드에서 동시에 사용할 수 있습니다. 그러나 확장 메서드를 ConcurrentBag<T> 포함하여 구현된 인터페이스 중 하나를 통해 액세스하는 멤버는 스레드로부터 안전하게 보호되지 않으며 호출자가 동기화해야 할 수도 있습니다.