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


C# TransformBlock.AsObservable方法代码示例

本文整理汇总了C#中TransformBlock.AsObservable方法的典型用法代码示例。如果您正苦于以下问题:C# TransformBlock.AsObservable方法的具体用法?C# TransformBlock.AsObservable怎么用?C# TransformBlock.AsObservable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在TransformBlock的用法示例。


在下文中一共展示了TransformBlock.AsObservable方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

    static void Main(string[] args)
    {
        // 
        // Create the members of the pipeline. 
        //  

        // Downloads the requested resource as a string. 
        var downloadString = new TransformBlock<string, string>(uri =>
        {
            Console.WriteLine("Downloading '{0}'...", uri);

            return new WebClient().DownloadString(uri);
        });

        // Separates the specified text into an array of words. 
        var createWordList = new TransformBlock<string, string[]>(text =>
        {
            Console.WriteLine("Creating word list...");

            // Remove common punctuation by replacing all non-letter characters  
            // with a space character to. 
            char[] tokens = text.ToArray();
            for (int i = 0; i < tokens.Length; i++)
            {
                if (!char.IsLetter(tokens[i]))
                    tokens[i] = ' ';
            }
            text = new string(tokens);

            // Separate the text into an array of words. 
            return text.Split(new char[] { ' ' },
               StringSplitOptions.RemoveEmptyEntries);
        });

        // Removes short words, orders the resulting words alphabetically,  
        // and then remove duplicates. 
        var filterWordList = new TransformBlock<string[], string[]>(words =>
        {
            Console.WriteLine("Filtering word list...");

            return words.Where(word => word.Length > 3).OrderBy(word => word)
               .Distinct().ToArray();
        });

        // Finds all words in the specified collection whose reverse also  
        // exists in the collection. 
        var findReversedWords = new TransformManyBlock<string[], string>(words =>
        {
            Console.WriteLine("Finding reversed words...");

            // Holds reversed words. 
            var reversedWords = new ConcurrentQueue<string>();

            // Add each word in the original collection to the result whose  
            // reversed word also exists in the collection.
            Parallel.ForEach(words, word =>
            {
                // Reverse the work. 
                string reverse = new string(word.Reverse().ToArray());

                // Enqueue the word if the reversed version also exists 
                // in the collection. 
                if (Array.BinarySearch<string>(words, reverse) >= 0 &&
                    word != reverse)
                {
                    reversedWords.Enqueue(word);
                }
            });

            return reversedWords;
        });

        // Prints the provided reversed words to the console.     
        var printReversedWords = new ActionBlock<string>(reversedWord =>
        {
            Console.WriteLine("Found reversed words {0}/{1}",
               reversedWord, new string(reversedWord.Reverse().ToArray()));
        });

        // 
        // Connect the dataflow blocks to form a pipeline. 
        //

        downloadString.AsObservable().Subscribe(i => 
            Console.WriteLine("Action Sub {0}", i));

        var te= downloadString.AsObserver();


        downloadString.LinkTo(createWordList);
        createWordList.LinkTo(filterWordList);
        filterWordList.LinkTo(findReversedWords);
        findReversedWords.LinkTo(printReversedWords);

        // 
        // For each completion task in the pipeline, create a continuation task 
        // that marks the next block in the pipeline as completed. 
        // A completed dataflow block processes any buffered elements, but does 
        // not accept new elements. 
        //
//.........这里部分代码省略.........
开发者ID:denmerc,项目名称:Presentations,代码行数:101,代码来源:PipeLine.cs

示例2: TestAsObservableAndAsObserver_ErrorPropagation

        public async Task TestAsObservableAndAsObserver_ErrorPropagation()
        {
            // Test that exceptional data flows when exception occurs before and after subscription
            foreach (bool beforeSubscription in DataflowTestHelpers.BooleanValues)
            {
                var tb = new TransformBlock<int, int>(i => {
                    if (i == 42) throw new InvalidOperationException("uh oh");
                    return i;
                });

                if (beforeSubscription)
                {
                    tb.Post(42);
                    await Assert.ThrowsAsync<InvalidOperationException>(async () => await tb.Completion);
                }

                ITargetBlock<int>[] targets = Enumerable.Range(0, 3).Select(_ => new WriteOnceBlock<int>(i => i)).ToArray();
                foreach (var target in targets)
                {
                    tb.AsObservable().Subscribe(target.AsObserver());
                }

                if (!beforeSubscription)
                {
                    tb.Post(42);
                    await Assert.ThrowsAsync<InvalidOperationException>(() => tb.Completion);
                }

                foreach (var target in targets)
                {
                    await Assert.ThrowsAsync<AggregateException>(() => target.Completion);
                }
            }
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:34,代码来源:DataflowBlockExtensionTests.cs

示例3: Main

        public static void Main(string[] args)
        {
            var testObs = new TransformBlock<int, int>(item => item * item);
            var o = testObs.AsObservable ();

            o.Subscribe(i=> Console.WriteLine("Test Obs received {0}", i.ToString()));

            for (int i = 0; i < 5; i++) {
                testObs.Post (i);
            }

            testObs.Completion.Wait ();

            Console.ReadKey ();

            var buffer = new BufferBlock<int>();
            IObservable<int> integers = buffer.AsObservable();
            integers.Subscribe(data =>
                Console.WriteLine(data),
                ex => Console.WriteLine(ex),
                () => Console.WriteLine("Done"));

            buffer.Post(13);
            buffer.Post(14);
            buffer.Post(15);
            buffer.Post(16);

            Console.ReadKey ();

            IObservable<DateTimeOffset> ticks =
                Observable.Interval(TimeSpan.FromSeconds(1))
                    .Timestamp()
                    .Select(x => x.Timestamp)
                    .Take(5);

            var display = new ActionBlock<DateTimeOffset>(x => Console.WriteLine(x));
            ticks.Subscribe(display.AsObserver());

            Console.ReadKey ();

            try
            {
                display.Completion.Wait();
                Trace.WriteLine("Done.");
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }

            try
            {
                var multiplyBlock = new TransformBlock<int, int>(item =>
                    {
                    //	if (item == 1)
                    //		throw new InvalidOperationException("Blech.");

                 		return item * 2;
                    });

                var subtractBlock = new TransformBlock<int, int>(item => item - 2);
                multiplyBlock.LinkTo(subtractBlock);

                var printing = new ActionBlock<int>(i => Console.WriteLine("Received {0}", i.ToString()));

                subtractBlock.LinkTo(printing, new DataflowLinkOptions { PropagateCompletion = true });

                IObservable<int> obs = subtractBlock.AsObservable();
                obs.Subscribe(i => Console.WriteLine("Received Observable {0}", i.ToString()));

                for(int i = 0; i < 10;i++){
                    multiplyBlock.Post(i);
                    subtractBlock.Post(i);
                }

                Console.ReadLine ();
                //printing.Completion.Wait();
            }

            catch (AggregateException exception)
            {
                AggregateException ex = exception.Flatten();
                System.Diagnostics.Trace.WriteLine(ex.InnerException);
            }

            Console.WriteLine ("Hello World!");

            Console.ReadLine ();
        }
开发者ID:rikace,项目名称:Experiments,代码行数:89,代码来源:Program.cs


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