當前位置: 首頁>>代碼示例>>C#>>正文


C# IProducerConsumerCollection<T>接口代碼示例

本文整理匯總了C#中System.Collections.Concurrent.IProducerConsumerCollection<T>接口的典型用法代碼示例。如果您正苦於以下問題:C# IProducerConsumerCollection<T>接口的具體用法?C# IProducerConsumerCollection<T>怎麽用?C# IProducerConsumerCollection<T>使用的例子?那麽, 這裏精選的接口代碼示例或許可以為您提供幫助。


IProducerConsumerCollection<T>接口屬於System.Collections.Concurrent命名空間,在下文中一共展示了IProducerConsumerCollection<T>接口的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: object

//引入命名空間
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!!");
        }
    }
}
開發者ID:.NET開發者,項目名稱:System.Collections.Concurrent,代碼行數:204,代碼來源:IProducerConsumerCollection


注:本文中的System.Collections.Concurrent.IProducerConsumerCollection<T>接口示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。