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


C# BufferBlock.AsObservable方法代码示例

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


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

示例1: TestAsObservableAndAsObserver_BroadcastFaultyTarget

        public async Task TestAsObservableAndAsObserver_BroadcastFaultyTarget()
        {
            var targets = new ITargetBlock<int>[] 
            {
                new BufferBlock<int>(),
                new DelegatePropagator<int, int>() { OfferMessageDelegate = delegate { throw new InvalidOperationException(); } },
                new BufferBlock<int>()
            };

            var source = new BufferBlock<int>();
            foreach (var target in targets) source.AsObservable().Subscribe(target.AsObserver());

            source.Post(1);

            await Task.WhenAll(
                Assert.ThrowsAsync<AggregateException>(() => targets[0].Completion),
                Assert.ThrowsAsync<AggregateException>(() => targets[2].Completion));
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:18,代码来源:DataflowBlockExtensionTests.cs

示例2: TestAsObservableAndAsObserver_AsObservableDoesntLeak

        [OuterLoop] // stress test
        public void TestAsObservableAndAsObserver_AsObservableDoesntLeak()
        {
            const int Count = 1000;

            var blockReferences = new WeakReference<BufferBlock<int>>[Count];

            for (int i = 0; i < Count; i++)
            {
                var b = new BufferBlock<int>();
                var o = b.AsObservable();
                blockReferences[i] = new WeakReference<BufferBlock<int>>(b);
                b = null;
                o = null;
            }

            for (int i = 0; i < 1; i++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }

            int remaining = blockReferences.Count(wr => {
                BufferBlock<int> b;
                return wr.TryGetTarget(out b);
            });
            Assert.True(remaining <= 1);
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:29,代码来源:DataflowBlockExtensionTests.cs

示例3: TestAsObservableAndAsObserver_BroadcastBackPressure

        public async Task TestAsObservableAndAsObserver_BroadcastBackPressure()
        {
            var source = new BufferBlock<int>();
            var targets = new[]
            {
                new BufferBlock<int>(),
                new BufferBlock<int>(new DataflowBlockOptions() { BoundedCapacity = 1 }), // This target will apply back pressure
                new BufferBlock<int>()
            };

            // Link the observable to the observers
            var observable = source.AsObservable();
            foreach (var target in targets)
                observable.Subscribe(target.AsObserver());

            // Post first message. Since there is no pressure yet, all targets should accept it.
            source.Post(1);
            Task<int> first = targets[0].ReceiveAsync();
            Task<bool> second = targets[1].OutputAvailableAsync();
            Task<int> third = targets[2].ReceiveAsync();
            await Task.WhenAll(first, second, third);
            Assert.Equal(expected: 1, actual: first.Result);
            Assert.True(second.Result);
            Assert.Equal(expected: 1, actual: third.Result);

            // Post second message. Target2 will postpone, but target1 and target3 should accept it.
            source.Post(2);
            await Task.WhenAll(targets[0].ReceiveAsync(), targets[2].ReceiveAsync());

            // Post third message. No target should be offered the message, because the source should be waiting for target2 to accept second message.
            source.Post(3);
            Assert.False(targets[0].OutputAvailableAsync().IsCompleted); // there's a race here such that this test might be a nop, but
            Assert.False(targets[2].OutputAvailableAsync().IsCompleted); // there's no good way to test the absence of a push

            // Unblock target2 to let third message propagate. Then all targets should end up with a message.
            await Task.WhenAll(targets[1].ReceiveAsync(), targets[1].ReceiveAsync()); // clear two items from second target
            await Task.WhenAll(from target in targets select target.ReceiveAsync()); // clear third item from all targets

            // Complete the source which should complete all the targets
            source.Complete();
            await source.Completion;
            await Task.WhenAll(from target in targets select target.Completion);
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:43,代码来源:DataflowBlockExtensionTests.cs

示例4: TestAsObservableAndAsObserver_LinkAndUnlink

        public void TestAsObservableAndAsObserver_LinkAndUnlink()
        {
            var b = new BufferBlock<int>();
            var o = b.AsObservable();
            for (int i = 0; i < 2; i++)
            {
                IDisposable[] unlinkers = Enumerable.Range(0, 5).Select(_ => o.Subscribe(new DelegateObserver<int>())).ToArray();
                foreach (var unlinker in unlinkers) unlinker.Dispose();
                foreach (var unlinker in unlinkers) unlinker.Dispose(); // make sure it's ok to dispose twice
            }

            // Validate sane behavior with a bad LinkTo
            Assert.Null(
                new DelegatePropagator<int, int> {
                    LinkToDelegate = (_,__) => null
                }.AsObservable().Subscribe(DataflowBlock.NullTarget<int>().AsObserver()));
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:17,代码来源:DataflowBlockExtensionTests.cs

示例5: TestAsObservableAndAsObserver_AllObserversGetData

        public async Task TestAsObservableAndAsObserver_AllObserversGetData()
        {
            int total = 0;
            var options = new ExecutionDataflowBlockOptions { TaskScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler };
            ITargetBlock<int>[] targets = Enumerable.Range(0, 3).Select(_ => new ActionBlock<int>(i => total += i, options)).ToArray();

            var source = new BufferBlock<int>();
            var sourceObservable = source.AsObservable();
            foreach (var target in targets)
            {
                sourceObservable.Subscribe(target.AsObserver());
            }

            int expectedTotal = 0;
            for (int i = 1; i <= 10; i++)
            {
                expectedTotal += i * targets.Length;
                source.Post(i);
            }
            source.Complete();

            await source.Completion;
            foreach (var target in targets)
            {
                await target.Completion;
            }
            Assert.Equal(expected: expectedTotal, actual: total);
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:28,代码来源:DataflowBlockExtensionTests.cs

示例6: TestAsObservableAndAsObserver_AsObservableDoesntConsume

        public void TestAsObservableAndAsObserver_AsObservableDoesntConsume()
        {
            var b = new BufferBlock<int>();
            b.PostRange(0, 2);

            Assert.Equal(expected: 2, actual: b.Count);
            Assert.NotNull(b.AsObservable());
            Assert.Equal(expected: 2, actual: b.Count);
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:9,代码来源:DataflowBlockExtensionTests.cs

示例7: TestAsObservableAndAsObserver_ObservableIdempotency

        public void TestAsObservableAndAsObserver_ObservableIdempotency()
        {
            ISourceBlock<string> b1 = new BufferBlock<string>();
            ISourceBlock<string> b2 = new BufferBlock<string>();
            Assert.NotNull(b1.AsObservable());
            Assert.True(b1.AsObservable() == b1.AsObservable());
            Assert.True(b1.AsObservable() != b2.AsObservable());

            ISourceBlock<int> b4 = new BufferBlock<int>();
            ISourceBlock<int> b5 = new BufferBlock<int>();
            Assert.NotNull(b4.AsObservable());
            Assert.True(b4.AsObservable() == b4.AsObservable());
            Assert.True(b4.AsObservable() != b5.AsObservable());
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:14,代码来源:DataflowBlockExtensionTests.cs

示例8: TestAsObservableAndAsObserver_DataPropagation

        public async Task TestAsObservableAndAsObserver_DataPropagation()
        {
            // Test that preset data flows correctly
            {
                var bb = new BufferBlock<int>();
                bb.PostRange(0, 2);
                bb.Complete();

                int nextValueExpected = 0;
                var ab = new ActionBlock<int>(i => {
                    Assert.True(i == nextValueExpected, string.Format("Expected next value to be {0} but got {1}", nextValueExpected, i));
                    nextValueExpected++;
                });

                bb.AsObservable().Subscribe(ab.AsObserver());
                await ab.Completion;
            }

            // Test that new data flows correctly
            {
                int nextValueExpected = -2;
                var ab = new ActionBlock<int>(i => {
                    Assert.True(i == nextValueExpected, string.Format("Expected next value to be {0} but got {1}", nextValueExpected, i));
                    nextValueExpected++;
                });

                var bb = new BufferBlock<int>();
                bb.AsObservable().Subscribe(ab.AsObserver());

                bb.PostRange(-2, 0);
                bb.Complete();

                await ab.Completion;
            }

            // Test that unsubscribing stops flow of data and stops completion
            {
                var target = new BufferBlock<int>();
                var source = new BufferBlock<int>();

                using (source.AsObservable().Subscribe(target.AsObserver()))
                {
                    source.PostItems(1, 2);
                    Assert.Equal(expected: 1, actual: await target.ReceiveAsync());
                    Assert.Equal(expected: 2, actual: await target.ReceiveAsync());
                }

                source.Post(3);
                var wb = new WriteOnceBlock<int>(i => i);
                source.LinkTo(wb);
                await wb.Completion;

                source.Complete();
                await source.Completion;

                Assert.False(target.Completion.IsCompleted);
            }
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:58,代码来源:DataflowBlockExtensionTests.cs

示例9: TestAsObservableAndAsObserver_MixedTargets

        public async Task TestAsObservableAndAsObserver_MixedTargets()
        {
            var tcs = new TaskCompletionSource<int>();

            var source = new BufferBlock<int>();
            source.AsObservable().Subscribe(new DelegateObserver<int>
            {
                OnNextDelegate = i => tcs.TrySetResult(i)
            });

            source.Post(42);
            Assert.Equal(expected: 42, actual: await tcs.Task);
        }
开发者ID:gitter-badger,项目名称:corefx,代码行数:13,代码来源:DataflowBlockExtensionTests.cs

示例10: 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


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