ConcurrentStack<T> 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
스레드로부터 안전한 LIFO(Last In-First Out) 컬렉션을 나타냅니다.
generic <typename T>
public ref class ConcurrentStack : System::Collections::Concurrent::IProducerConsumerCollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IReadOnlyCollection<T>, System::Collections::ICollection
generic <typename T>
public ref class ConcurrentStack : System::Collections::Concurrent::IProducerConsumerCollection<T>, System::Collections::Generic::IEnumerable<T>
generic <typename T>
public ref class ConcurrentStack : System::Collections::Concurrent::IProducerConsumerCollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::Generic::IReadOnlyCollection<T>
generic <typename T>
public ref class ConcurrentStack : System::Collections::Concurrent::IProducerConsumerCollection<T>, System::Collections::Generic::IEnumerable<T>, System::Collections::ICollection
public class ConcurrentStack<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection
[System.Serializable]
public class ConcurrentStack<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>
[System.Serializable]
public class ConcurrentStack<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>
public class ConcurrentStack<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection
public class ConcurrentStack<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>
type ConcurrentStack<'T> = class
interface IProducerConsumerCollection<'T>
interface seq<'T>
interface IEnumerable
interface ICollection
interface IReadOnlyCollection<'T>
[<System.Serializable>]
type ConcurrentStack<'T> = class
interface IProducerConsumerCollection<'T>
interface seq<'T>
interface ICollection
interface IEnumerable
[<System.Serializable>]
type ConcurrentStack<'T> = class
interface IProducerConsumerCollection<'T>
interface seq<'T>
interface IEnumerable
interface ICollection
interface IReadOnlyCollection<'T>
type ConcurrentStack<'T> = class
interface IProducerConsumerCollection<'T>
interface seq<'T>
interface ICollection
interface IEnumerable
Public Class ConcurrentStack(Of T)
Implements ICollection, IEnumerable(Of T), IProducerConsumerCollection(Of T), IReadOnlyCollection(Of T)
Public Class ConcurrentStack(Of T)
Implements IEnumerable(Of T), IProducerConsumerCollection(Of T)
Public Class ConcurrentStack(Of T)
Implements IEnumerable(Of T), IProducerConsumerCollection(Of T), IReadOnlyCollection(Of T)
Public Class ConcurrentStack(Of T)
Implements ICollection, IEnumerable(Of T), IProducerConsumerCollection(Of T)
형식 매개 변수
- T
스택에 포함된 요소의 형식입니다.
- 상속
-
ConcurrentStack<T>
- 특성
- 구현
예제
다음 예제에서는 ConcurrentStack<T> 사용하여 개별 항목을 푸시하고 팝하는 방법을 보여줍니다.
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
class Example
{
// Demonstrates:
// ConcurrentStack<T>.Push();
// ConcurrentStack<T>.TryPeek();
// ConcurrentStack<T>.TryPop();
// ConcurrentStack<T>.Clear();
// ConcurrentStack<T>.IsEmpty;
static async Task Main()
{
int items = 10000;
ConcurrentStack<int> stack = new ConcurrentStack<int>();
// Create an action to push items onto the stack
Action pusher = () =>
{
for (int i = 0; i < items; i++)
{
stack.Push(i);
}
};
// Run the action once
pusher();
if (stack.TryPeek(out int result))
{
Console.WriteLine($"TryPeek() saw {result} on top of the stack.");
}
else
{
Console.WriteLine("Could not peek most recently added number.");
}
// Empty the stack
stack.Clear();
if (stack.IsEmpty)
{
Console.WriteLine("Cleared the stack.");
}
// Create an action to push and pop items
Action pushAndPop = () =>
{
Console.WriteLine($"Task started on {Task.CurrentId}");
int item;
for (int i = 0; i < items; i++)
stack.Push(i);
for (int i = 0; i < items; i++)
stack.TryPop(out item);
Console.WriteLine($"Task ended on {Task.CurrentId}");
};
// Spin up five concurrent tasks of the action
var tasks = new Task[5];
for (int i = 0; i < tasks.Length; i++)
tasks[i] = Task.Factory.StartNew(pushAndPop);
// Wait for all the tasks to finish up
await Task.WhenAll(tasks);
if (!stack.IsEmpty)
{
Console.WriteLine("Did not take all the items off the stack");
}
}
}
open System
open System.Collections.Concurrent
open System.Threading.Tasks
// Demonstrates:
// ConcurrentStack<T>.Push();
// ConcurrentStack<T>.TryPeek();
// ConcurrentStack<T>.TryPop();
// ConcurrentStack<T>.Clear();
// ConcurrentStack<T>.IsEmpty;
let main =
task {
let items = 10000
let stack = ConcurrentStack<int>()
// Create an action to push items onto the stack
let pusher =
Action(fun () ->
for i = 0 to items - 1 do
stack.Push i)
// Run the action once
pusher.Invoke()
let mutable result = 0
if stack.TryPeek &result then
printfn $"TryPeek() saw {result} on top of the stack."
else
printfn "Could not peek most recently added number."
// Empty the stack
stack.Clear()
if stack.IsEmpty then
printfn "Cleared the stack."
// Create an action to push and pop items
let pushAndPop =
Action(fun () ->
printfn $"Task started on {Task.CurrentId}"
let mutable item = 0
for i = 0 to items - 1 do
stack.Push i
for i = 0 to items - 1 do
stack.TryPop &item |> ignore
printfn $"Task ended on {Task.CurrentId}")
// Spin up five concurrent tasks of the action
let tasks =
[| for i = 0 to 4 do
Task.Run pushAndPop |]
// Wait for all the tasks to finish up
do! Task.WhenAll tasks
if not stack.IsEmpty then
printfn "Did not take all the items off the stack"
}
main.Wait()
Imports System.Collections.Concurrent
Imports System.Threading.Tasks
Class Example
' Demonstrates:
' ConcurrentStack<T>.Push();
' ConcurrentStack<T>.TryPeek();
' ConcurrentStack<T>.TryPop();
' ConcurrentStack<T>.Clear();
' ConcurrentStack<T>.IsEmpty;
Shared Sub Main()
Dim items As Integer = 10000
Dim stack As ConcurrentStack(Of Integer) = New ConcurrentStack(Of Integer)()
' Create an action to push items onto the stack
Dim pusher As Action = Function()
For i As Integer = 0 To items - 1
stack.Push(i)
Next
End Function
' Run the action once
pusher()
Dim result As Integer = Nothing
If stack.TryPeek(result) Then
Console.WriteLine($"TryPeek() saw {result} on top of the stack.")
Else
Console.WriteLine("Could not peek most recently added number.")
End If
' Empty the stack
stack.Clear()
If stack.IsEmpty Then
Console.WriteLine("Cleared the stack.")
End If
' Create an action to push and pop items
Dim pushAndPop As Action = Function()
Console.WriteLine($"Task started on {Task.CurrentId}")
Dim item As Integer
For i As Integer = 0 To items - 1
stack.Push(i)
Next
For i As Integer = 0 To items - 1
stack.TryPop(item)
Next
Console.WriteLine($"Task ended on {Task.CurrentId}")
End Function
' Spin up five concurrent tasks of the action
Dim tasks = New Task(4) {}
For i As Integer = 0 To tasks.Length - 1
tasks(i) = Task.Factory.StartNew(pushAndPop)
Next
' Wait for all the tasks to finish up
Task.WaitAll(tasks)
If Not stack.IsEmpty Then
Console.WriteLine("Did not take all the items off the stack")
End If
End Sub
End Class
다음 예제에서는 ConcurrentStack<T> 사용하여 항목 범위를 푸시하고 팝하는 방법을 보여 줍니다.
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
class Example
{
// Demonstrates:
// ConcurrentStack<T>.PushRange();
// ConcurrentStack<T>.TryPopRange();
static async Task Main()
{
int numParallelTasks = 4;
int numItems = 1000;
var stack = new ConcurrentStack<int>();
// Push a range of values onto the stack concurrently
await Task.WhenAll(Enumerable.Range(0, numParallelTasks).Select(i => Task.Factory.StartNew((state) =>
{
// state = i * numItems
int index = (int)state;
int[] array = new int[numItems];
for (int j = 0; j < numItems; j++)
{
array[j] = index + j;
}
Console.WriteLine($"Pushing an array of ints from {array[0]} to {array[numItems - 1]}");
stack.PushRange(array);
}, i * numItems, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)).ToArray());
int numTotalElements = 4 * numItems;
int[] resultBuffer = new int[numTotalElements];
await Task.WhenAll(Enumerable.Range(0, numParallelTasks).Select(i => Task.Factory.StartNew(obj =>
{
int index = (int)obj;
int result = stack.TryPopRange(resultBuffer, index, numItems);
Console.WriteLine($"TryPopRange expected {numItems}, got {result}.");
}, i * numItems, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray());
for (int i = 0; i < numParallelTasks; i++)
{
// Create a sequence we expect to see from the stack taking the last number of the range we inserted
var expected = Enumerable.Range(resultBuffer[i*numItems + numItems - 1], numItems);
// Take the range we inserted, reverse it, and compare to the expected sequence
var areEqual = expected.SequenceEqual(resultBuffer.Skip(i * numItems).Take(numItems).Reverse());
if (areEqual)
{
Console.WriteLine($"Expected a range of {expected.First()} to {expected.Last()}. Got {resultBuffer[i * numItems + numItems - 1]} to {resultBuffer[i * numItems]}");
}
else
{
Console.WriteLine($"Unexpected consecutive ranges.");
}
}
}
}
open System.Collections.Concurrent
open System.Linq
open System.Threading
open System.Threading.Tasks
// Demonstrates:
// ConcurrentStack<T>.PushRange();
// ConcurrentStack<T>.TryPopRange();
let main =
task {
let numParallelTasks = 4
let numItems = 1000
let stack = ConcurrentStack<int>()
// Push a range of values onto the stack concurrently
let! _ = Task.WhenAll(Enumerable.Range(0, numParallelTasks).Select(fun i ->
Task.Factory.StartNew((fun state ->
// state = i * numItems
let index: int = unbox state
let array =
[| for j in 0 .. numItems - 1 do
index + j |]
printfn $"Pushing an array of ints from {array[0]} to {array[numItems - 1]}"
stack.PushRange array
), i * numItems, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)).ToArray())
let numTotalElements = 4 * numItems
let resultBuffer = Array.zeroCreate numTotalElements
let! _ = Task.WhenAll(Enumerable.Range(0, numParallelTasks).Select(fun i ->
Task.Factory.StartNew((fun obj ->
let index = unbox obj
let result = stack.TryPopRange(resultBuffer, index, numItems)
printfn $"TryPopRange expected {numItems}, got {result}."
), i * numItems, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray())
for i = 0 to numParallelTasks - 1 do
// Create a sequence we expect to see from the stack taking the last number of the range we inserted
let expected = Enumerable.Range(resultBuffer[i*numItems + numItems - 1], numItems)
// Take the range we inserted, reverse it, and compare to the expected sequence
let areEqual = expected.SequenceEqual(resultBuffer.Skip(i * numItems).Take(numItems).Reverse())
if areEqual then
printfn $"Expected a range of {expected.First()} to {expected.Last()}. Got {resultBuffer[i * numItems + numItems - 1]} to {resultBuffer[i * numItems]}"
else
printfn $"Unexpected consecutive ranges."
}
main.Wait()
Imports System.Collections.Concurrent
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Class Example
' Demonstrates:
' ConcurrentStack<T>.PushRange();
' ConcurrentStack<T>.TryPopRange();
Shared Sub Main()
Dim numParallelTasks As Integer = 4
Dim numItems As Integer = 1000
Dim stack = New ConcurrentStack(Of Integer)()
' Push a range of values onto the stack concurrently
Task.WaitAll(Enumerable.Range(0, numParallelTasks).[Select](
Function(i) Task.Factory.StartNew(
Function(state)
Dim index As Integer = CInt(state)
Dim array As Integer() = New Integer(numItems - 1) {}
For j As Integer = 0 To numItems - 1
array(j) = index + j
Next
Console.WriteLine($"Pushing an array of ints from {array(0)} to {array(numItems - 1)}")
stack.PushRange(array)
End Function, i * numItems, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.[Default])).ToArray())
Dim numTotalElements As Integer = 4 * numItems
Dim resultBuffer As Integer() = New Integer(numTotalElements - 1) {}
Task.WaitAll(Enumerable.Range(0, numParallelTasks).[Select](
Function(i) Task.Factory.StartNew(
Function(obj)
Dim index As Integer = CInt(obj)
Dim result As Integer = stack.TryPopRange(resultBuffer, index, numItems)
Console.WriteLine($"TryPopRange expected {numItems}, got {result}.")
End Function, i * numItems, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.[Default])).ToArray())
For i As Integer = 0 To numParallelTasks - 1
' Create a sequence we expect to see from the stack taking the last number of the range we inserted
Dim expected = Enumerable.Range(resultBuffer(i * numItems + numItems - 1), numItems)
' Take the range we inserted, reverse it, and compare to the expected sequence
Dim areEqual = expected.SequenceEqual(resultBuffer.Skip(i * numItems).Take(numItems).Reverse())
If areEqual Then
Console.WriteLine($"Expected a range of {expected.First()} to {expected.Last()}. Got {resultBuffer(i * numItems + numItems - 1)} to {resultBuffer(i * numItems)}")
Else
Console.WriteLine($"Unexpected consecutive ranges.")
End If
Next
End Sub
End Class
설명
메모
ConcurrentStack<T> .NET Framework 4.6부터 IReadOnlyCollection<T> 인터페이스를 구현합니다. 이전 버전의 .NET Framework에서 ConcurrentStack<T> 클래스는 이 인터페이스를 구현하지 않았습니다.
ConcurrentStack<T> 몇 가지 주요 작업을 제공합니다.
Push ConcurrentStack<T>맨 위에 요소를 삽입합니다.
TryPop ConcurrentStack<T>맨 위에서 요소를 제거하거나 항목을 제거할 수 없는 경우
false
반환합니다.TryPeek ConcurrentStack<T> 맨 위에 있지만 ConcurrentStack<T>제거하지 않는 요소를 반환합니다.
TryPopRange 및 PushRange 메서드는 단일 작업에서 여러 요소의 효율적인 푸시 및 팝을 제공합니다.
생성자
ConcurrentStack<T>() |
ConcurrentStack<T> 클래스의 새 인스턴스를 초기화합니다. |
ConcurrentStack<T>(IEnumerable<T>) |
지정된 컬렉션에서 복사한 요소를 포함하는 ConcurrentStack<T> 클래스의 새 인스턴스를 초기화합니다. |
속성
Count |
ConcurrentStack<T>포함된 요소 수를 가져옵니다. |
IsEmpty |
ConcurrentStack<T> 비어 있는지 여부를 나타내는 값을 가져옵니다. |
메서드
Clear() |
ConcurrentStack<T>모든 개체를 제거합니다. |
CopyTo(T[], Int32) |
지정된 배열 인덱스에서 시작하여 ConcurrentStack<T> 요소를 기존 1차원 Array복사합니다. |
Equals(Object) |
지정된 개체가 현재 개체와 같은지 여부를 확인합니다. (다음에서 상속됨 Object) |
GetEnumerator() |
ConcurrentStack<T>반복하는 열거자를 반환합니다. |
GetHashCode() |
기본 해시 함수로 사용됩니다. (다음에서 상속됨 Object) |
GetType() |
현재 인스턴스의 Type 가져옵니다. (다음에서 상속됨 Object) |
MemberwiseClone() |
현재 Object단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
Push(T) |
ConcurrentStack<T>맨 위에 개체를 삽입합니다. |
PushRange(T[]) |
ConcurrentStack<T> 맨 위에 여러 개체를 원자성으로 삽입합니다. |
PushRange(T[], Int32, Int32) |
ConcurrentStack<T> 맨 위에 여러 개체를 원자성으로 삽입합니다. |
ToArray() |
ConcurrentStack<T> 저장된 항목을 새 배열에 복사합니다. |
ToString() |
현재 개체를 나타내는 문자열을 반환합니다. (다음에서 상속됨 Object) |
TryPeek(T) |
개체를 제거하지 않고 ConcurrentStack<T> 맨 위에서 개체를 반환하려고 시도합니다. |
TryPop(T) |
ConcurrentStack<T>맨 위에 있는 개체를 팝하고 반환하려고 시도합니다. |
TryPopRange(T[]) |
ConcurrentStack<T> 맨 위에서 여러 개체를 원자성으로 팝하고 반환하려고 시도합니다. |
TryPopRange(T[], Int32, Int32) |
ConcurrentStack<T> 맨 위에서 여러 개체를 원자성으로 팝하고 반환하려고 시도합니다. |
명시적 인터페이스 구현
ICollection.CopyTo(Array, Int32) |
특정 Array 인덱스에서 시작하여 ICollection 요소를 Array복사합니다. |
ICollection.IsSynchronized |
ICollection 대한 액세스가 SyncRoot와 동기화되는지 여부를 나타내는 값을 가져옵니다. |
ICollection.SyncRoot |
ICollection대한 액세스를 동기화하는 데 사용할 수 있는 개체를 가져옵니다. 이 속성은 지원되지 않습니다. |
IEnumerable.GetEnumerator() |
컬렉션을 반복하는 열거자를 반환합니다. |
IProducerConsumerCollection<T>.TryAdd(T) |
IProducerConsumerCollection<T>개체를 추가하려고 합니다. |
IProducerConsumerCollection<T>.TryTake(T) |
IProducerConsumerCollection<T>개체를 제거하고 반환하려고 합니다. |
확장 메서드
적용 대상
스레드 보안
ConcurrentStack<T> 모든 공용 및 보호된 멤버는 스레드로부터 안전하며 여러 스레드에서 동시에 사용할 수 있습니다.
추가 정보
.NET