static void Main(string[] args)
            {
                var numbers  = new MySequenceOfNumbers();
                var observer = new MyConsoleObserver <int>();

                numbers.Subscribe(observer);
            }
Example #2
0
        public void Run()
        {
            var numbers  = new MySequenceOfNumbers();
            var observer = new MyConsoleObserver <int>();

            numbers.Subscribe(observer);

            //Received value 1
            //Received value 2
            //Received value 3
            //Sequence terminated
        }
Example #3
0
        static async Task Main(string[] args)
        {
            Form1 f = new Form1();

            f.ShowDialog();
            //TaskScheduler.Current
            //在From程序中可传递UI线程的上下文
            //var uiContext = SynchronizationContext.Current;
            WriteLine($"UI线程ID:{CurrentThread.ManagedThreadId}");
            Observable.Interval(TimeSpan.FromSeconds(1))
            .ObserveOn(Scheduler.Default)
            .Subscribe(x => WriteLine($"Interval {x} On Thread:{Environment.CurrentManagedThreadId}"));
            WriteLine("----------分割线----------");
            ReadLine();
            var timer = new System.Timers.Timer(1000)
            {
                Enabled = true
            };
            //方法1
            //var ticks = Observable.FromEventPattern<ElapsedEventHandler, ElapsedEventArgs>(
            //    //转换器  ElapsedEventHandler转换成ElapsedEventArgs
            //    handler => (s, a) => handler(s, a),
            //    //订阅退阅
            //    handler => timer.Elapsed += handler,
            //    handler => timer.Elapsed -= handler
            //    );
            //方法2
            //使用反射机制,转换并订阅退订Timer的Elapsed事件
            var ticks = Observable.FromEventPattern(timer, "Elapsed");

            //data.EventArgs依然是强类型
            ticks.Subscribe(data => WriteLine($"On Next:{((ElapsedEventArgs)data.EventArgs).SignalTime}"));
            //ticks.Subscribe(data => WriteLine($"On Next:{data.EventArgs.SignalTime}"));



            var progress = new Progress <int>();
            //订阅与退订
            var progressSupports = Observable.FromEventPattern <int>(
                handler => progress.ProgressChanged += handler,
                handler => progress.ProgressChanged -= handler
                );

            //data.EventArg是强类型的int
            progressSupports.Subscribe(data => WriteLine($"On Next:{data.EventArgs}"));


            var mulitplyBlock = new TransformBlock <int, int>(
                item => item * 2,
                new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
            }
                );
            var substract = new TransformBlock <int, int>(item => item - 2);

            //mulitplyBlock相当于那个需要计算量很大的数据流块,所以开启了并行处理的方式
            //上面的设置,可以允许执行任意数量的并行任务
            mulitplyBlock.LinkTo(substract);

            var sourceBuffer = new BufferBlock <int>();
            var operation    = new DataflowBlockOptions {
                BoundedCapacity = 1
            };
            var targetA = new BufferBlock <int>(operation);
            var targetB = new BufferBlock <int>(operation);

            //A的缓冲区>1时,数据会流向B
            sourceBuffer.LinkTo(targetA);
            sourceBuffer.LinkTo(targetB);


            var mutliplayBlock = new TransformBlock <int, int>(item => item * 2);
            var subtractBlock  = new TransformBlock <int, int>(item => item - 2);

            //建立连接后,从mutliplayBlock出来的数据将进入subtractBlock
            mutliplayBlock.LinkTo(subtractBlock);

            var options = new DataflowLinkOptions {
                PropagateCompletion = true
            };

            mutliplayBlock.LinkTo(subtractBlock, options);
            //....
            //第一块的完成的情况自动传递给第二个块
            mutliplayBlock.Complete();
            await subtractBlock.Completion;

            int[] demoInts   = new int[] { 1, 2, 3 };
            int   intResult  = ParallelSum(demoInts);
            int   pinqresult = PLINQSum(demoInts);//结果:6

            Task <int> TaskA     = DelayAndReturnAsync(3);
            Task <int> TaskB     = DelayAndReturnAsync(2);
            Task <int> TaskC     = DelayAndReturnAsync(1);
            var        taskArray = new[] { TaskA, TaskB, TaskC };

            foreach (var item in taskArray.OrderByCompletion())
            {
                var rr = await item;
                Trace.Write($"Task Order Result:{rr}");
            }
            WriteLine("-------------------------");
            ReadLine();

            taskArray = new[] { TaskA, TaskB, TaskC };
            var processTasks = (from t in taskArray select AwaitAndProcessAsync(t)).ToArray();
            await Task.WhenAll(processTasks);

            WriteLine("-------------------------");
            ReadLine();
            foreach (var t in taskArray)
            {
                var rrTask = await t;
                Trace.Write($"Trace:{rrTask}");
            }
            ReadLine();
            //await--等待异步方法执行完成并获取结果
            int Mathresult = await MathTaskDemo();

            WriteLine(Mathresult.ToString());


            #region ReplaySubject <T>缓存值的功能,然后为任何延迟订阅重播它们
            var sub2 = new ReplaySubject <string>();
            sub2.OnNext("a");
            WriteSequenceToConsole(sub2);
            sub2.OnNext("b");
            sub2.OnNext("c");
            Console.ReadKey();

            var sub1 = new Subject <string>();
            sub1.OnNext("a");
            //我们已经将我们的第一个数据移到我们的订阅之前
            WriteSequenceToConsole(sub1);
            sub1.OnNext("b");
            sub1.OnNext("c");
            Console.ReadKey();
            #endregion


            #region 0628Rx响应式编程学习
            WriteLine("IObserable的抽象实现----------");
            //IObserable的抽象实现
            var subject = new Subject <string>();
            WriteSequenceToConsole(subject);
            subject.OnNext("a");
            subject.OnNext("b");
            subject.OnNext("c");
            Console.ReadKey();

            #endregion

            #region 0627Rx响应式编程学习
            var numbers  = new MySequenceOfNumbers();
            var observer = new MyConsoleObserver <int>();
            numbers.Subscribe(observer);
            Console.ReadLine();
            #endregion



            #region 生产者消费者模拟
            Console.WriteLine("生产者消费者模拟......");
            for (int i = 1; i < 9; i++)
            {
                Thread T1 = new Thread(new ThreadStart(Producer));
                Thread T2 = new Thread(new ThreadStart(Customer));
                T1.Name = String.Format("生产者线程{0}", i);
                T2.Name = String.Format("消费者线程{0}", i);
                T1.Start();
                T2.Start();
            }
            Console.ReadKey();
            #endregion

            #region 进程互斥
            for (int i = 0; i <= numThreads; i++)
            {
                Thread myThread = new Thread(new ThreadStart(UseResource));
                myThread.Name = String.Format("线程{0}", i + 1);
                myThread.Start();
            }
            Console.ReadKey();
            #endregion

            #region 进程同步(同一进程不同线程处理同一个任务)
            Console.WriteLine("进程1执行完了进程2才能执行.......");
            Thread Thread1 = new Thread(new ThreadStart(Proc1));
            Thread Thread2 = new Thread(new ThreadStart(Proc2));
            Thread1.Start();
            Thread2.Start();
            Console.ReadKey();
            #endregion

            #region 0613Linq使用探索

            foreach (int item in YieldGetList(5))
            {
                Console.WriteLine(item);
            }

            foreach (int item in GetList(5))
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();

            #endregion

            //.SubscribeOn(NewThreadScheduler.Default)
            #region 使用SubscribeOn控制订阅(subscribing)的上下文
            WriteLine("Starting on threadId:{0}", Thread.CurrentThread.ManagedThreadId);
            var source = Observable.Create <int>(
                s =>
            {
                WriteLine("Invoked on threadId:{0}", Thread.CurrentThread.ManagedThreadId);
                s.OnNext(1);
                s.OnNext(2);
                s.OnNext(3);
                s.OnCompleted();
                WriteLine("Finished on threadId:{0}",
                          CurrentThread.ManagedThreadId);
                return(Disposable.Empty);
            });
            source
            .SubscribeOn(CurrentThreadScheduler.Instance)
            .Subscribe(
                s => WriteLine("Received {1} on threadId:{0}",
                               CurrentThread.ManagedThreadId,
                               s),
                () => WriteLine("OnCompleted on threadId:{0}",
                                CurrentThread.ManagedThreadId));
            WriteLine("Subscribed on threadId:{0}", Thread.CurrentThread.ManagedThreadId);
            Read();
            #endregion

            #region Rx默认工作模式探索
            WriteLine("Starting on threadId:{0}", CurrentThread.ManagedThreadId);
            var sub = new Subject <Object>();
            //订阅元素处理程序到可观察序列。
            sub.Subscribe(oo => WriteLine("Received {1} on threadId:{0}",//为Observable订阅处理器(handler)输出handler thread id
                                          CurrentThread.ManagedThreadId,
                                          oo));
            ParameterizedThreadStart notify = obj =>//委托定义,其内输出被观察对象的thread id
            {
                //打印放进队列的value
                WriteLine("OnNext({1}) on threadId:{0}",
                          CurrentThread.ManagedThreadId,
                          obj);
                //在序列中通知所有订阅的观察者指定元素的到达情况
                //obj为传递到序列的新函数
                sub.OnNext(obj);
            };
            notify(1);
            new Thread(notify).Start(2);
            new Thread(notify).Start(3);
            WriteLine("Enter to add new value to queue");
            ReadLine();
            new Thread(notify).Start(5);
            ReadLine();
            #endregion

            #region 0610使用TPL数据流库来实现并行管道
            var TPLDemp = ProcessAsyncChronous();
            //通知所有等待线程,结束等待,开始执行
            TPLDemp.GetAwaiter().GetResult();
            WriteLine($"使用TPL数据流库来实现并行管道运行完成!");
            ReadLine();
            #endregion

            #region 使用BlockingCollection实现并行管道
            var cts = new CancellationTokenSource();
            Task.Run(() =>
            {
                if (ReadKey().KeyChar == 'c')
                {
                    cts.Cancel();
                }
            }, cts.Token);

            var sourceArrays = new BlockingCollection <int> [CollectionNumber];
            for (int i = 0; i < sourceArrays.Length; i++)
            {
                sourceArrays[i] = new BlockingCollection <int>(Count);
            }
            //Func有参有返回值的委托方法
            var convertToDecimal = new PiplineWorker <int, decimal>(sourceArrays,
                                                                    n => Convert.ToDecimal(n * 100),
                                                                    cts.Token, "Decimal Converter");
            //Action有参无返回值委托方法
            var stringifyNumber = new PiplineWorker <decimal, string>(convertToDecimal.Output,
                                                                      s => WriteLine($"--{s.ToString("C", CultureInfo.GetCultureInfo("en-us"))}"),
                                                                      cts.Token, "String Formatter");

            var outputResultToConsole = new PiplineWorker <string, string>(stringifyNumber.
                                                                           Output, s => WriteLine($"The final result is {s} on thread" + $"{CurrentThread.ManagedThreadId}"),
                                                                           cts.Token, "Console Output");

            try
            {
                Parallel.Invoke(
                    () => CreateInitialValues(sourceArrays, cts),
                    () => convertToDecimal.Run(),
                    () => stringifyNumber.Run(),
                    () => outputResultToConsole.Run()
                    );
            }
            catch (AggregateException ae)
            {
                foreach (var ex in ae.InnerExceptions)
                {
                    WriteLine(ex.Message + ex.StackTrace);
                }
            }
            if (cts.Token.IsCancellationRequested)
            {
                WriteLine("Operation has been canceled! Press Enter to exit.");
            }
            else
            {
                WriteLine("Press Enter to exit.");
            }
            WriteLine("使用BlockingCollection实现并行管道Demo执行完成........");
            ReadLine();

            #endregion

            #region 普通遍历与推送订阅模式(基于Rx库)对比
            //-----普通遍历与推送订阅模式对比---------
            foreach (var e in EnumerableEventSequence())
            {
                Write(e);
            }
            WriteLine();
            WriteLine("IEnumberable");
            IObservable <int> o = EnumerableEventSequence().ToObservable();
            using (IDisposable d = o.Subscribe(Write))
            {
                WriteLine();
                WriteLine("IObservable");
            }
            o = EnumerableEventSequence().ToObservable().SubscribeOn(TaskPoolScheduler.Default);
            using (IDisposable subscription = o.Subscribe(Write))
            {
                WriteLine();
                WriteLine("IObservable async");
                ReadLine();
            }
            WriteLine("-------------");
            WriteLine("Rx库使用示例-----1");
            #endregion

            #region PLinq并行查询--Parallel并行执行函数 05-28之前
            ReadLine();
            var PLinqDemo = from t in GetTypes().AsParallel() select EmulateProcessing(t);

            var ppcts = new CancellationTokenSource();
            ppcts.CancelAfter(TimeSpan.FromSeconds(3));
            try
            {
                //调整并行查询参数
                PLinqDemo.WithDegreeOfParallelism(Environment.ProcessorCount)
                .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                .WithMergeOptions(ParallelMergeOptions.Default)
                .WithCancellation(ppcts.Token)
                .ForAll(WriteLine);
            }
            catch (OperationCanceledException e)
            {
                WriteLine("-------------");
                WriteLine("Operation has been canceled.");
            }
            //-------------------------------------------------------------
            WriteLine("-------------");
            WriteLine("Unordered PLINQ query execution.");
            //无序并行查询
            var unOrderderQuery = from t in ParallelEnumerable.Range(1, 30) select t;
            foreach (var item in unOrderderQuery)
            {
                WriteLine(item);
            }
            //-------------------------------------------------------------
            WriteLine("-------------");
            WriteLine("ordered PLINQ query execution.");
            //顺序并行查询
            var orderedQuery = from t in ParallelEnumerable.Range(1, 30).AsOrdered() select t;
            foreach (var item in orderedQuery)
            {
                WriteLine(item);
            }
            WriteLine("-------------调整Parallel并行查询参数到此结束!-----------------");
            ReadLine();
            //-------------------------------------------------------------
            Stopwatch sw = new Stopwatch();
            sw.Start();
            //方式1
            //单例查询 速度最慢 单例遍历
            var Query = from t in GetTypes() select EmulateProcessing(t);

            foreach (string typeName in Query)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            WriteLine("-------------");
            WriteLine("Sequential Linq Query.");
            WriteLine($"Time elspsed:{sw.Elapsed}");
            WriteLine("Please Enter to continue...");
            ReadLine();
            sw.Reset();
            //-----------------------------------------------------------------------------
            sw.Start();
            //方式2
            //查询并行化,结果单线程遍历
            var parallelQuery = from t in GetTypes().AsParallel()//启用查询并行化
                                select EmulateProcessing(t);

            foreach (string typeName in parallelQuery)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            WriteLine("-------------");
            WriteLine($"Paralle Linq Query.The results are being merged on a single thread");
            WriteLine($"Time elspsed:{sw.Elapsed}");
            WriteLine("Please Enter to continue...");
            ReadLine();
            sw.Reset();
            //-----------------------------------------------------------------------------
            sw.Start();
            //方式3
            //查询并行 遍历并行
            parallelQuery = from t in GetTypes().AsParallel() select EmulateProcessing(t);

            //使用指定的操作为每个元素并行调用source
            //遍历并行
            parallelQuery.ForAll(PrintInfo);
            sw.Stop();
            WriteLine("-------------");
            WriteLine("Parallel Linq Query.The result are being processed in parallel");
            WriteLine($"Time elspsed:{sw.Elapsed}");
            WriteLine("Please Enter to continue...");
            ReadLine();
            sw.Reset();
            //-----------------------------------------------------------------------------
            sw.Start();
            //方式4
            //并行运算强制转换成顺序运算,单例遍历,效率最低
            Query = from t in GetTypes().AsParallel().AsSequential() select EmulateProcessing(t);

            foreach (string typeName in Query)
            {
                PrintInfo(typeName);
            }
            sw.Stop();
            WriteLine("-------------");
            WriteLine("Parallel Linq Query.transformed into sequential");
            WriteLine($"Time elspsed:{sw.Elapsed}");
            WriteLine("Please Enter to continue...");
            ReadLine();



            WriteLine("-------------Parallel并行查询到此结束!-----------------");
            ReadLine();
            //尽可能并行执行提供的每个操作
            //NameSpace:System.Threading.Tasks
            Parallel.Invoke(() => EmulateProcessing("Task1"),
                            () => EmulateProcessing("Task2"),
                            () => EmulateProcessing("Task3")
                            );

            var pcts = new CancellationTokenSource();
            //并行迭代
            var result = Parallel.ForEach(Enumerable.Range(1, 30),

                                          new ParallelOptions()
            {
                CancellationToken      = pcts.Token,
                MaxDegreeOfParallelism = Environment.ProcessorCount,
                TaskScheduler          = TaskScheduler.Default
            },

                                          (i, state) =>
            {
                WriteLine(i);
                if (i == 20)
                {
                    //告知 System.Threading.Tasks.Parallel 循环应在系统方便的时候尽早停止执行当前迭代之外的迭代。
                    state.Break();
                    WriteLine($"Loop is Stop:{state.IsStopped}");
                }
            });
            WriteLine("-------------");
            //获取指示循环已完成运行,以便所有的循环迭代期间执行,并且该循环没有收到提前结束的请求。
            WriteLine($"Is Completed:{result.IsCompleted}");
            //从中获取的最低迭代索引 System.Threading.Tasks.ParallelLoopState.Break 调用。
            WriteLine($"Lowest break iteration:{result.LowestBreakIteration}");

            WriteLine("-------------||-----------------");
            ReadLine();
            Task tq = MyAsyncWithAwaitQuickly();
            tq.Wait();
            //Task tl = MyAsyncWithAwaitLow();
            //tl.Wait();

            WriteLine("------------------------------");
            ReadLine();
            Task t1 = AsyncLambda();
            t1.Wait();
            #endregion
        }
Example #4
0
 public static void Run()
 {
     var numbers = new MySequenceOfNumbers();
       var observer = new MyConsoleObserver<int>();
       numbers.Subscribe(observer);
 }