Esempio n. 1
0
        public static void RunPipelineFilter()
        {
            //Generate the source data.
            var source = new BlockingCollection <int> [3];

            for (int i = 0; i < source.Length; i++)
            {
                source[i] = new BlockingCollection <int>(100);
            }

            Parallel.For(0, source.Length * 100, (data) =>
            {
                int item = BlockingCollection <int> .TryAddToAny(source, data);
                if (item >= 0)
                {
                    Console.WriteLine("added {0} to source data", data);
                }
            });

            foreach (var array in source)
            {
                array.CompleteAdding();
            }

            // calculate the square
            var calculateFilter = new PipelineFilter <int, int>(source,
                                                                (n) => n * n,
                                                                "calculateFilter"
                                                                );

            //Convert ints to strings
            var convertFilter = new PipelineFilter <int, string>
                                (
                calculateFilter.m_outputData,
                (s) => String.Format("{0}", s),
                "convertFilter"
                                );

            // Displays the results
            var displayFilter = new PipelineFilter <string, string>
                                (
                convertFilter.m_outputData,
                (s) => Console.WriteLine("The final result is {0}", s),
                "displayFilter");

            // Start the pipeline
            try
            {
                Parallel.Invoke(
                    () => calculateFilter.Run(),
                    () => convertFilter.Run(),
                    () => displayFilter.Run()
                    );
            }
            catch (AggregateException aggregate)
            {
                foreach (var exception in aggregate.InnerExceptions)
                {
                    Console.WriteLine(exception.Message + exception.StackTrace);
                }
            }

            Console.ReadLine();
        }
Esempio n. 2
0
    public static void Main()
    {
        CancellationTokenSource cts = new CancellationTokenSource();

        // Start up a UI thread for cancellation.
        Task.Run(() =>
        {
            if (Console.ReadKey(true).KeyChar == 'c')
            {
                cts.Cancel();
            }
        });

        //Generate some source data.
        BlockingCollection <int>[] sourceArrays = new BlockingCollection <int> [5];
        for (int i = 0; i < sourceArrays.Length; i++)
        {
            sourceArrays[i] = new BlockingCollection <int>(500);
        }
        Parallel.For(0, sourceArrays.Length * 500, (j) =>
        {
            int k = BlockingCollection <int> .TryAddToAny(sourceArrays, j);
            if (k >= 0)
            {
                Console.WriteLine("added {0} to source data", j);
            }
        });

        foreach (var arr in sourceArrays)
        {
            arr.CompleteAdding();
        }

        // First filter accepts the ints, keeps back a small percentage
        // as a processing fee, and converts the results to decimals.
        var filter1 = new PipelineFilter <int, decimal>
                      (
            sourceArrays,
            (n) => Convert.ToDecimal(n * 0.97),
            cts.Token,
            "filter1"
                      );

        // Second filter accepts the decimals and converts them to
        // System.Strings.
        var filter2 = new PipelineFilter <decimal, string>
                      (
            filter1.m_output,
            (s) => String.Format("{0}", s),
            cts.Token,
            "filter2"
                      );

        // Third filter uses the constructor with an Action<T>
        // that renders its output to the screen,
        // not a blocking collection.
        var filter3 = new PipelineFilter <string, string>
                      (
            filter2.m_output,
            (s) => Console.WriteLine("The final result is {0}", s),
            cts.Token,
            "filter3"
                      );

        // Start up the pipeline!
        try
        {
            Parallel.Invoke(
                () => filter1.Run(),
                () => filter2.Run(),
                () => filter3.Run()
                );
        }
        catch (AggregateException ae) {
            foreach (var ex in ae.InnerExceptions)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
            }
        }
        finally {
            cts.Dispose();
        }
        // You will need to press twice if you ran to the end:
        // once for the cancellation thread, and once for this thread.
        Console.WriteLine("Press any key.");
        Console.ReadKey(true);
    }
        public static void Main()
        {
            var cts = new System.Threading.CancellationTokenSource();
            var ct  = cts.Token;
            var sw  = Stopwatch.StartNew();

            BlockingCollection <string>[] sourceSentences = new BlockingCollection <string> [5];
            for (int i = 0; i < sourceSentences.Length; i++)
            {
                sourceSentences[i] = new BlockingCollection <string>(NUM_SENTENCES / 5);
            }

            string[] possibleSentences =
            {
                "ConcurrentBag is included in the System.Collections.Concurrent namespace.",
                "Is parallelism important for cloud-computing?",
                "Parallelism is very important for cloud-computing!",
                "ConcurrentQueue is one of the new concurrent collections added in .NET Framework 4",
                "ConcurrentStack is a concurrent collection that represents a LIFO collection",
                "ConcurrentQueue is a concurrent collection that represents a FIFO collection"
            };

            Parallel.For(0, NUM_SENTENCES, (sentenceNumber) =>
            {
                BlockingCollection <string> .TryAddToAny(
                    sourceSentences,
                    ProduceASentence(possibleSentences),
                    50);
            });

            for (int j = 0; j < sourceSentences.Length; j++)
            {
                sourceSentences[j].CompleteAdding();
            }

            char[] delimiterChars =
            { ' ',    ',', '.', ':', ';', '(', ')',  '[',
              ']', '{', '}', '/', '?', '@', '\t', '"' };

            var filterCapitalizeWords = new PipelineFilter <string, string>
                                        (
                sourceSentences,
                (sentence) => CapitalizeWords(
                    delimiterChars, sentence, '\\'),
                ct,
                "CapitalizeWords"
                                        );

            char[] letterChars =
            { 'A',    'B', 'C', 'e', 'i',
              'j', 'm', 'X', 'y', 'Z' };
            var filterRemoveLetters = new PipelineFilter <string, string>
                                      (
                filterCapitalizeWords.Output,
                (sentence) => RemoveLetters(letterChars, sentence),
                ct,
                "RemoveLetters"
                                      );

            var filterWriteLine = new PipelineFilter <string, string>
                                  (
                filterRemoveLetters.Output,
                (sentence) => Console.WriteLine(sentence),
                ct,
                "WriteLine"
                                  );

            var deferredCancelTask = Task.Factory.StartNew(() =>
            {
                // Sleep the thread that runs this task for 2 seconds
                System.Threading.Thread.Sleep(2000);
                // Send the signal to cancel
                cts.Cancel();
            });

            try
            {
                Parallel.Invoke(
                    () => filterCapitalizeWords.Run(),
                    () => filterRemoveLetters.Run(),
                    () => filterWriteLine.Run()
                    );
            }
            catch (AggregateException ex)
            {
                foreach (var innerEx in ex.InnerExceptions)
                {
                    Console.WriteLine(innerEx.Message);
                }
            }

            Debug.WriteLine(sw.Elapsed.ToString());
            //  Display the results and wait for the user to press a key
            Console.WriteLine("Finished!");
            Console.ReadLine();
        }
        public static void Main()
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            // Start up a UI thread for cancellation.
            Task.Run(() =>
            {
                if (Console.ReadKey(true).KeyChar == 'c')
                    cts.Cancel();
            });

            //Generate some source data.
            BlockingCollection<int>[] sourceArrays = new BlockingCollection<int>[5];
            for (int i = 0; i < sourceArrays.Length; i++)
                sourceArrays[i] = new BlockingCollection<int>(500);
            Parallel.For(0, sourceArrays.Length * 500, (j) =>
            {
                int k = BlockingCollection<int>.TryAddToAny(sourceArrays, j);
                if (k >= 0)
                    Console.WriteLine("added {0} to source data", j);
            });

            foreach (var arr in sourceArrays)
                arr.CompleteAdding();

            // First filter accepts the ints, keeps back a small percentage
            // as a processing fee, and converts the results to decimals.
            var filter1 = new PipelineFilter<int, decimal>
            (
                sourceArrays,
                (n) => Convert.ToDecimal(n * 0.97), // Func
                cts.Token,
                "filter1"
             );

            // Second filter accepts the decimals and converts them to
            // System.Strings.
            var filter2 = new PipelineFilter<decimal, string>
            (
                filter1.m_output,
                (s) => String.Format("{0}", s), // Func
                cts.Token,
                "filter2"
             );

            // Third filter uses the constructor with an Action<T>
            // that renders its output to the screen,
            // not a blocking collection.
            var filter3 = new PipelineFilter<string, string>
            (
                filter2.m_output,
                (s) => Console.WriteLine("The final result is {0}", s), // Action
                cts.Token,
                "filter3"
             );

            // Start up the pipeline!
            try
            {
                Parallel.Invoke(
                             () => filter1.Run(),
                             () => filter2.Run(),
                             () => filter3.Run()
                         );
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.InnerExceptions)
                    Console.WriteLine(ex.Message + ex.StackTrace);
            }
            finally
            {
                cts.Dispose();
            }
            // You will need to press twice if you ran to the end:
            // once for the cancellation thread, and once for this thread.
            Console.WriteLine("Press any key.");
            Console.ReadKey(true);
        }