当前位置: 首页>>代码示例>>C#>>正文


C# ConcurrentStack<T>类代码示例

本文整理汇总了C#中System.Collections.Concurrent.ConcurrentStack<T>的典型用法代码示例。如果您正苦于以下问题:C# ConcurrentStack<T>类的具体用法?C# ConcurrentStack<T>怎么用?C# ConcurrentStack<T>使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ConcurrentStack<T>类属于System.Collections.Concurrent命名空间,在下文中一共展示了ConcurrentStack<T>类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

//引入命名空间
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");
        }
    }
}
开发者ID:.NET开发者,项目名称:System.Collections.Concurrent,代码行数:76,代码来源:ConcurrentStack

示例2: Main

//引入命名空间
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.");
            }   
        }
    }
}
开发者ID:.NET开发者,项目名称:System.Collections.Concurrent,代码行数:61,代码来源:ConcurrentStack


注:本文中的System.Collections.Concurrent.ConcurrentStack<T>类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。