IProducerConsumerCollection<T> Interface
Définition
Définit de méthodes de manipulation des collections thread-safe destinées à l'utilisation des producteurs/consommateurs.Defines methods to manipulate thread-safe collections intended for producer/consumer usage. Cette interface fournit une représentation unifiée pour les collections producteur/consommateur afin que les abstractions de niveau supérieur, telles que BlockingCollection<T>, puissent utiliser la collection comme mécanisme de stockage sous-jacent.This interface provides a unified representation for producer/consumer collections so that higher level abstractions such as BlockingCollection<T> can use the collection as the underlying storage mechanism.
generic <typename T>
public interface class IProducerConsumerCollection : System::Collections::Generic::IEnumerable<T>, System::Collections::ICollection
public interface IProducerConsumerCollection<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection
type IProducerConsumerCollection<'T> = interface
interface seq<'T>
interface ICollection
interface IEnumerable
Public Interface IProducerConsumerCollection(Of T)
Implements ICollection, IEnumerable(Of T)
Paramètres de type
- T
Spécifie le type d'éléments de la collection.Specifies the type of elements in the collection.
- Dérivé
- Implémente
Exemples
L’exemple suivant montre une structure de données de pile qui implémente System.Collections.Concurrent.IProducerConsumerCollection<T>.The following example shows a stack data structure that implements System.Collections.Concurrent.IProducerConsumerCollection<T>.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
// Sample implementation of IProducerConsumerCollection(T)
// -- in this case, a thread-safe stack.
public class SafeStack<T> : IProducerConsumerCollection<T>
{
// Used for enforcing thread-safety
private object m_lockObject = new object();
// We'll use a regular old Stack for our core operations
private Stack<T> m_sequentialStack = null;
//
// Constructors
//
public SafeStack()
{
m_sequentialStack = new Stack<T>();
}
public SafeStack(IEnumerable<T> collection)
{
m_sequentialStack = new Stack<T>(collection);
}
//
// Safe Push/Pop support
//
public void Push(T item)
{
lock (m_lockObject) m_sequentialStack.Push(item);
}
public bool TryPop(out T item)
{
bool rval = true;
lock (m_lockObject)
{
if (m_sequentialStack.Count == 0) { item = default(T); rval = false; }
else item = m_sequentialStack.Pop();
}
return rval;
}
//
// IProducerConsumerCollection(T) support
//
public bool TryTake(out T item)
{
return TryPop(out item);
}
public bool TryAdd(T item)
{
Push(item);
return true; // Push doesn't fail
}
public T[] ToArray()
{
T[] rval = null;
lock (m_lockObject) rval = m_sequentialStack.ToArray();
return rval;
}
public void CopyTo(T[] array, int index)
{
lock (m_lockObject) m_sequentialStack.CopyTo(array, index);
}
//
// Support for IEnumerable(T)
//
public IEnumerator<T> GetEnumerator()
{
// The performance here will be unfortunate for large stacks,
// but thread-safety is effectively implemented.
Stack<T> stackCopy = null;
lock (m_lockObject) stackCopy = new Stack<T>(m_sequentialStack);
return stackCopy.GetEnumerator();
}
//
// Support for IEnumerable
//
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
//
// Support for ICollection
//
public bool IsSynchronized
{
get { return true; }
}
public object SyncRoot
{
get { return m_lockObject; }
}
public int Count
{
get { return m_sequentialStack.Count; }
}
public void CopyTo(Array array, int index)
{
lock (m_lockObject) ((ICollection)m_sequentialStack).CopyTo(array, index);
}
}
public class Program
{
static void Main()
{
TestSafeStack();
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
// Test our implementation of IProducerConsumerCollection(T)
// Demonstrates:
// IPCC(T).TryAdd()
// IPCC(T).TryTake()
// IPCC(T).CopyTo()
static void TestSafeStack()
{
SafeStack<int> stack = new SafeStack<int>();
IProducerConsumerCollection<int> ipcc = (IProducerConsumerCollection<int>)stack;
// Test Push()/TryAdd()
stack.Push(10); Console.WriteLine("Pushed 10");
ipcc.TryAdd(20); Console.WriteLine("IPCC.TryAdded 20");
stack.Push(15); Console.WriteLine("Pushed 15");
int[] testArray = new int[3];
// Try CopyTo() within boundaries
try
{
ipcc.CopyTo(testArray, 0);
Console.WriteLine("CopyTo() within boundaries worked, as expected");
}
catch (Exception e)
{
Console.WriteLine("CopyTo() within boundaries unexpectedly threw an exception: {0}", e.Message);
}
// Try CopyTo() that overflows
try
{
ipcc.CopyTo(testArray, 1);
Console.WriteLine("CopyTo() with index overflow worked, and it SHOULD NOT HAVE");
}
catch (Exception e)
{
Console.WriteLine("CopyTo() with index overflow threw an exception, as expected: {0}", e.Message);
}
// Test enumeration
Console.Write("Enumeration (should be three items): ");
foreach (int item in stack) Console.Write("{0} ", item);
Console.WriteLine("");
// Test TryPop()
int popped = 0;
if (stack.TryPop(out popped))
{
Console.WriteLine("Successfully popped {0}", popped);
}
else Console.WriteLine("FAILED to pop!!");
// Test Count
Console.WriteLine("stack count is {0}, should be 2", stack.Count);
// Test TryTake()
if (ipcc.TryTake(out popped))
{
Console.WriteLine("Successfully IPCC-TryTaked {0}", popped);
}
else Console.WriteLine("FAILED to IPCC.TryTake!!");
}
}
Imports System.Collections.Concurrent
Module IProdCon
' Sample implementation of IProducerConsumerCollection(T) -- in this case,
' a thread-safe stack.
Public Class SafeStack(Of T)
Implements IProducerConsumerCollection(Of T)
' Used for enforcing thread-safety
Private m_lockObject As New Object()
' We'll use a regular old Stack for our core operations
Private m_sequentialStack As Stack(Of T) = Nothing
'
' Constructors
'
Public Sub New()
m_sequentialStack = New Stack(Of T)()
End Sub
Public Sub New(ByVal collection As IEnumerable(Of T))
m_sequentialStack = New Stack(Of T)(collection)
End Sub
'
' Safe Push/Pop support
'
Public Sub Push(ByVal item As T)
SyncLock m_lockObject
m_sequentialStack.Push(item)
End SyncLock
End Sub
Public Function TryPop(ByRef item As T) As Boolean
Dim rval As Boolean = True
SyncLock m_lockObject
If m_sequentialStack.Count = 0 Then
item = Nothing
rval = False
Else
item = m_sequentialStack.Pop()
End If
End SyncLock
Return rval
End Function
'
' IProducerConsumerCollection(T) support
'
Public Function TryTake(ByRef item As T) As Boolean Implements IProducerConsumerCollection(Of T).TryTake
Return TryPop(item)
End Function
Public Function TryAdd(ByVal item As T) As Boolean Implements IProducerConsumerCollection(Of T).TryAdd
Push(item)
' Push doesn't fail
Return True
End Function
Public Function ToArray() As T() Implements IProducerConsumerCollection(Of T).ToArray
Dim rval As T() = Nothing
SyncLock m_lockObject
rval = m_sequentialStack.ToArray()
End SyncLock
Return rval
End Function
Public Sub CopyTo(ByVal array As T(), ByVal index As Integer) Implements IProducerConsumerCollection(Of T).CopyTo
SyncLock m_lockObject
m_sequentialStack.CopyTo(array, index)
End SyncLock
End Sub
'
' Support for IEnumerable(T)
'
Public Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
' The performance here will be unfortunate for large stacks,
' but thread-safety is effectively implemented.
Dim stackCopy As Stack(Of T) = Nothing
SyncLock m_lockObject
stackCopy = New Stack(Of T)(m_sequentialStack)
End SyncLock
Return stackCopy.GetEnumerator()
End Function
'
' Support for IEnumerable
'
Private Function GetEnumerator2() As IEnumerator Implements IEnumerable.GetEnumerator
Return DirectCast(Me, IEnumerable(Of T)).GetEnumerator()
End Function
'
' Support for ICollection
'
Public ReadOnly Property IsSynchronized() As Boolean Implements ICollection.IsSynchronized
Get
Return True
End Get
End Property
Public ReadOnly Property SyncRoot() As Object Implements ICollection.SyncRoot
Get
Return m_lockObject
End Get
End Property
Public ReadOnly Property Count() As Integer Implements ICollection.Count
Get
Return m_sequentialStack.Count
End Get
End Property
Public Sub CopyTo(ByVal array As Array, ByVal index As Integer) Implements ICollection.CopyTo
SyncLock m_lockObject
DirectCast(m_sequentialStack, ICollection).CopyTo(array, index)
End SyncLock
End Sub
End Class
' Test our implementation of IProducerConsumerCollection(T)
' Demonstrates:
' IPCC(T).TryAdd()
' IPCC(T).TryTake()
' IPCC(T).CopyTo()
Private Sub TestSafeStack()
Dim stack As New SafeStack(Of Integer)()
Dim ipcc As IProducerConsumerCollection(Of Integer) = DirectCast(stack, IProducerConsumerCollection(Of Integer))
' Test Push()/TryAdd()
stack.Push(10)
Console.WriteLine("Pushed 10")
ipcc.TryAdd(20)
Console.WriteLine("IPCC.TryAdded 20")
stack.Push(15)
Console.WriteLine("Pushed 15")
Dim testArray As Integer() = New Integer(2) {}
' Try CopyTo() within boundaries
Try
ipcc.CopyTo(testArray, 0)
Console.WriteLine("CopyTo() within boundaries worked, as expected")
Catch e As Exception
Console.WriteLine("CopyTo() within boundaries unexpectedly threw an exception: {0}", e.Message)
End Try
' Try CopyTo() that overflows
Try
ipcc.CopyTo(testArray, 1)
Console.WriteLine("CopyTo() with index overflow worked, and it SHOULD NOT HAVE")
Catch e As Exception
Console.WriteLine("CopyTo() with index overflow threw an exception, as expected: {0}", e.Message)
End Try
' Test enumeration
Console.Write("Enumeration (should be three items): ")
For Each item As Integer In stack
Console.Write("{0} ", item)
Next
Console.WriteLine("")
' Test TryPop()
Dim popped As Integer = 0
If stack.TryPop(popped) Then
Console.WriteLine("Successfully popped {0}", popped)
Else
Console.WriteLine("FAILED to pop!!")
End If
' Test Count
Console.WriteLine("stack count is {0}, should be 2", stack.Count)
' Test TryTake()
If ipcc.TryTake(popped) Then
Console.WriteLine("Successfully IPCC-TryTaked {0}", popped)
Else
Console.WriteLine("FAILED to IPCC.TryTake!!")
End If
End Sub
Sub Main()
TestSafeStack()
' Keep the console window open in debug mode
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
End Sub
End Module
Remarques
Pour plus d’informations, consultez collections thread-safe et vue d’ensemble de BlockingCollection.For more information, see Thread-Safe Collections and BlockingCollection Overview.
Propriétés
Count |
Obtient le nombre d'éléments contenus dans le ICollection.Gets the number of elements contained in the ICollection. (Hérité de ICollection) |
IsSynchronized |
Obtient une valeur indiquant si l'accès à ICollection est synchronisé (thread-safe).Gets a value indicating whether access to the ICollection is synchronized (thread safe). (Hérité de ICollection) |
SyncRoot |
Obtient un objet qui peut être utilisé pour synchroniser l'accès à ICollection.Gets an object that can be used to synchronize access to the ICollection. (Hérité de ICollection) |
Méthodes
CopyTo(Array, Int32) |
Copie les éléments de ICollection dans Array, à partir d'un index particulier de Array.Copies the elements of the ICollection to an Array, starting at a particular Array index. (Hérité de ICollection) |
CopyTo(T[], Int32) |
Copie les éléments de IProducerConsumerCollection<T> dans Array, en commençant à un index spécifié.Copies the elements of the IProducerConsumerCollection<T> to an Array, starting at a specified index. |
GetEnumerator() |
Retourne un énumérateur qui itère au sein d’une collection.Returns an enumerator that iterates through a collection. (Hérité de IEnumerable) |
ToArray() |
Copie les éléments contenus dans IProducerConsumerCollection<T> dans un nouveau tableau.Copies the elements contained in the IProducerConsumerCollection<T> to a new array. |
TryAdd(T) |
Tente d'ajouter un objet à IProducerConsumerCollection<T>.Attempts to add an object to the IProducerConsumerCollection<T>. |
TryTake(T) |
Tente de supprimer et de retourner un objet du IProducerConsumerCollection<T>.Attempts to remove and return an object from the IProducerConsumerCollection<T>. |
Méthodes d’extension
CopyToDataTable<T>(IEnumerable<T>) |
Retourne un DataTable qui contient des copies des objets DataRow, à partir d'un objet d'entrée IEnumerable<T> où le paramètre générique |
CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) |
Copie les objets DataRow vers le DataTable spécifié, à partir d'un objet d'entrée IEnumerable<T> où le paramètre générique |
CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) |
Copie les objets DataRow vers le DataTable spécifié, à partir d'un objet d'entrée IEnumerable<T> où le paramètre générique |
Cast<TResult>(IEnumerable) |
Effectue un cast des éléments d'un IEnumerable vers le type spécifié.Casts the elements of an IEnumerable to the specified type. |
OfType<TResult>(IEnumerable) |
Filtre les éléments d'un IEnumerable en fonction du type spécifié.Filters the elements of an IEnumerable based on a specified type. |
AsParallel(IEnumerable) |
Active la parallélisation d'une requête.Enables parallelization of a query. |
AsQueryable(IEnumerable) |
Convertit un IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable. |
Ancestors<T>(IEnumerable<T>) |
Retourne une collection d'éléments qui contient les ancêtres de chaque nœud de la collection source.Returns a collection of elements that contains the ancestors of every node in the source collection. |
Ancestors<T>(IEnumerable<T>, XName) |
Retourne une collection d'éléments filtrée qui contient les ancêtres de chaque nœud de la collection source.Returns a filtered collection of elements that contains the ancestors of every node in the source collection. Seuls les éléments avec un XName correspondant sont inclus dans la collection.Only elements that have a matching XName are included in the collection. |
DescendantNodes<T>(IEnumerable<T>) |
Retourne une collection des nœuds descendants de chaque document et élément de la collection source.Returns a collection of the descendant nodes of every document and element in the source collection. |
Descendants<T>(IEnumerable<T>) |
Retourne une collection d'éléments qui contient les éléments descendants de tous les éléments et tous les documents de la collection source.Returns a collection of elements that contains the descendant elements of every element and document in the source collection. |
Descendants<T>(IEnumerable<T>, XName) |
Retourne une collection d'éléments filtrée qui contient les éléments descendants de tous les éléments et tous les documents de la collection source.Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. Seuls les éléments avec un XName correspondant sont inclus dans la collection.Only elements that have a matching XName are included in the collection. |
Elements<T>(IEnumerable<T>) |
Retourne une collection des éléments enfants de chaque élément et document de la collection source.Returns a collection of the child elements of every element and document in the source collection. |
Elements<T>(IEnumerable<T>, XName) |
Retourne une collection filtrée des éléments enfants de chaque élément et document de la collection source.Returns a filtered collection of the child elements of every element and document in the source collection. Seuls les éléments avec un XName correspondant sont inclus dans la collection.Only elements that have a matching XName are included in the collection. |
InDocumentOrder<T>(IEnumerable<T>) |
Retourne une collection de nœuds qui contient tous les nœuds de la collection source, triés selon l'ordre des documents.Returns a collection of nodes that contains all nodes in the source collection, sorted in document order. |
Nodes<T>(IEnumerable<T>) |
Retourne une collection des nœuds enfants de chaque document et élément de la collection source.Returns a collection of the child nodes of every document and element in the source collection. |
Remove<T>(IEnumerable<T>) |
Supprime chaque nœud de la collection source de son nœud parent.Removes every node in the source collection from its parent node. |
S’applique à
Cohérence de thread
Toutes les implémentations de cette interface doivent permettre l’utilisation simultanée de tous les membres de cette interface à partir de plusieurs threads.All implementations of this interface must enable all members of this interface to be used concurrently from multiple threads.