Ejemplo n.º 1
0
        private static void PassingState()
        {
            var scheduler = new NewThreadScheduler();
            var myName    = "Lee";

            //WRONG WAY
            //scheduler.Schedule(() => { Console.WriteLine($"{nameof(myName)} = {myName}"); });

            //CORRECT
            scheduler.Schedule(myName,
                               (_, state) =>
            {
                Console.WriteLine(state);
                return(Disposable.Empty);
            });
            myName = "John";

            //DO NOT DO THAT, shared list was modified
            var list = new List <int>();

            scheduler.Schedule(list,
                               (innerScheduler, state) =>
            {
                Console.WriteLine(state.Count);
                return(Disposable.Empty);
            });
            list.Add(1);
        }
Ejemplo n.º 2
0
        public Form1()
        {
            InitializeComponent();

            SynchronizationContextScheduler UIThread = new SynchronizationContextScheduler(SynchronizationContext.Current);
            NewThreadScheduler NewThread             = new NewThreadScheduler();

            client = new RestClient(Stash.baseUrl);
            timer  = new Stopwatch();

            var keyPressed = Observable
                             .FromEventPattern <KeyEventArgs>(textBox2, nameof(Control.KeyDown))
                             .Where(x => x.EventArgs.KeyCode == Keys.Enter)
                             .Subscribe(x => this.textBoxDown(x.Sender, x.EventArgs));

            pro1 = Observable
                   .FromAsync(ct => Stash.GetProjectsAsync(client, 25, ct))
                   .SubscribeOn(NewThread);

            clock = Observable
                    .Interval(TimeSpan.FromSeconds(0.1))
                    .Select(_ => timer.Elapsed)
                    .TakeWhile(_ => timer.IsRunning)
                    .ObserveOn(UIThread);
        }
Ejemplo n.º 3
0
        public static void NewThreadScheduler_BuildsNewEventLoopSchedulers_ForEachTopLevelScheduledActions()
        {
            //Execution Context: Dedicated (i.e. provided) Thread
            //Execution Policy: FIFO (trampolined  / message queue)
            //Clock: Machine Time

            Console.WriteLine("Before");
            var newThreadScheduler = new NewThreadScheduler();

            ScheduleTasksWithPassedOnScheduler(newThreadScheduler);

            /*Output:
             * outer start. on thread T0
             * outer end.
             * --innerAction start. on thread T0
             * --innerAction end.
             * ----leafAction. on thread T0
             */

            Console.ReadLine();
            ScheduleTasksWithPassedOnScheduler(newThreadScheduler);

            /*Output:
             * outer start. on thread T1
             * outer end.
             * --innerAction start. on thread T1
             * --innerAction end.
             * ----leafAction. on thread T1
             */

            Console.WriteLine("After");
        }
Ejemplo n.º 4
0
        public MainWindowViewModel(MainWindowModel model)
        {
            _newThreadScheduler = new NewThreadScheduler();

            Packages = model.PackageKeys
                       .Select(x => new PackageControlViewModel(x))
                       .ToObservable()
                       .ToReactiveCollection();

            UiSwitch = new ReactiveProperty <bool>(true);

            SelectedSolutionProperty = new ReactiveProperty <string>();
            var reactivePropertyObserverBridgeStringReplace = new ReactivePropertyObserverBridgeStringReplace(SelectedSolutionProperty);

            ReportString = new ReactiveProperty <string>(string.Empty);
            var reactivePropertyObserverBridgeStringAdd = new ReactivePropertyObserverBridgeStringAdd(ReportString);

            SelectSolutionCommand = new ReactiveCommand(UiSwitch);
            SelectSolutionCommand.Select(x => SelectSolutionToInspect())
            .Where(x => x != null)
            .Do(
                x =>
            {
                UiSwitch.Value     = false;
                ReportString.Value = string.Empty;
            })
            .Do(reactivePropertyObserverBridgeStringReplace)
            .Select(Anazyle)
            .Switch()
            .Timestamp()
            .Select(x => $"[{x.Timestamp:s}] {x.Value}")
            .Subscribe(reactivePropertyObserverBridgeStringAdd);
        }
Ejemplo n.º 5
0
 public SchedulerProvider()
 {
     Task = new TaskScheduler();
     IOCompletion = new IOCompletionScheduler();
     Current = new CurrentScheduler();
     Immediate = new ImmediateScheduler();
     NewThread = new NewThreadScheduler();
     ThreadPool = new ThreadPoolScheduler();
 }
Ejemplo n.º 6
0
 public SchedulerProvider()
 {
     Task         = new TaskScheduler();
     IOCompletion = new IOCompletionScheduler();
     Current      = new CurrentScheduler();
     Immediate    = new ImmediateScheduler();
     NewThread    = new NewThreadScheduler();
     ThreadPool   = new ThreadPoolScheduler();
 }
 public void Cancellation()
 {
     bool raised = false;
     var dis = new NewThreadScheduler ().Schedule<object> (null, TimeSpan.FromMilliseconds (300), (sch, stat) => raised = true);
     Assert.IsFalse (raised, "#1");
     dis.Dispose (); // immediately, to not raise event.
     Thread.Sleep (400);
     Assert.IsFalse (raised, "#2");
 }
Ejemplo n.º 8
0
        public void Cancellation()
        {
            bool raised = false;
            var  dis    = new NewThreadScheduler().Schedule <object> (null, TimeSpan.FromMilliseconds(300), (sch, stat) => raised = true);

            Assert.IsFalse(raised, "#1");
            dis.Dispose();              // immediately, to not raise event.
            Thread.Sleep(400);
            Assert.IsFalse(raised, "#2");
        }
Ejemplo n.º 9
0
        private static void FutureScheduling()
        {
            var scheduler = new NewThreadScheduler();
            var delay     = TimeSpan.FromSeconds(1);

            Console.WriteLine("Before schedule at {0:o}", DateTime.Now);
            scheduler.Schedule(delay,
                               () => Console.WriteLine("Inside schedule at {0:o}", DateTime.Now));
            Console.WriteLine("After schedule at  {0:o}", DateTime.Now);
        }
Ejemplo n.º 10
0
 public ReactiveWorkerService(IConsistentHash <Node> hash, IEventThreadRepository eventThreadRepository,
                              IEventRepository eventRepository, IWorkerRepository workerRepository, ILogger <ReactiveWorkerService> logger,
                              IOptions <Node> settings) : base(hash, eventThreadRepository, eventRepository, workerRepository, logger,
                                                               settings)
 {
     _scheduler = new NewThreadScheduler(ts => new Thread(ts)
     {
         Name = "Emitter scheduler"
     });
     _subject = new BehaviorSubject <IEnumerable <int> >(Enumerable.Empty <int>());
 }
Ejemplo n.º 11
0
        private void attachUIEvents()
        {
            var cancel = new CancellationDisposable();

            var scheduler = new NewThreadScheduler(t => new Thread(t)
            {
                Name = "Thread1"
            });
            var gridSch = new ControlScheduler(dataGridFile);

            var obRead = Observer.Create <EventPattern <object> >(o =>
            {
                //wait a moment
                //non blocking
                Thread.Sleep(5000);

                string[] lines = getLinesFromFile();

                if (lines != null)
                {
                    lines.ToObservable().ObserveOn(gridSch)
                    .Subscribe(l =>
                    {
                        addLineToGrid(l);
                    });
                }
            });

            var obWrite = Observer.Create <EventPattern <object> >(o =>
            {
                Thread.Sleep(5000);
                appendLinesToFile();
            });

            Observable.FromEventPattern(
                h => this.btnReadFile.Click += h,
                h => this.btnReadFile.Click -= h)
            .ObserveOn(scheduler)
            .Subscribe(obRead, cancel.Token);

            Observable.FromEventPattern(
                h => this.btnWriteFile.Click += h,
                h => this.btnWriteFile.Click -= h)
            .ObserveOn(scheduler)
            .Subscribe(obWrite, cancel.Token);

            Observable.FromEventPattern(
                h => Application.ApplicationExit += h,
                h => Application.ApplicationExit -= h)
            .Subscribe(_ => {
                cancel.Dispose();
            });
        }
 public void ScheduleAbsolute()
 {
     var s = new NewThreadScheduler ();
     bool flag = false;
     s.Schedule (s.Now.AddMilliseconds (200), () => flag = true);
     Thread.Sleep (200);
     Assert.IsTrue (flag, "#1");
     flag = false;
     var dis = s.Schedule (s.Now.AddMilliseconds (200), () => flag = true);
     dis.Dispose ();
     Thread.Sleep (200); // make sure to wait for timer
     Assert.IsFalse (flag, "#2");
 }
        public IObservable <RawBusMessage> StartConsuming(CancellationToken token, TimeSpan interval)
        {
            //-----------------------------------
            //--------- Observable.Generate
            var scheduler = new NewThreadScheduler(ts => new Thread(ts)
            {
                Name = "DataBusPoller"
            });
            var source = Observable.Generate(Read(),
                                             x => !token.IsCancellationRequested,
                                             x => Read(),
                                             x => x,
                                             x => interval,
                                             scheduler);

            return(source);

            //-----------------------------------
            //--------- Observable.Create
            //IObservable<RawBusMessage> source = Observable.Create(async (IObserver<RawBusMessage> observer) =>
            //{
            //    try
            //    {
            //        while (!token.IsCancellationRequested)
            //        {
            //            observer.OnNext(Read());
            //            await Task.Delay(interval);
            //        }

            //        observer.OnCompleted();
            //    }
            //    catch (Exception ex)
            //    {
            //        observer.OnError(ex);
            //    }

            //    return Disposable.Empty;
            //});

            //return source;

            //-----------------------------------
            //--------- Observable.Timer
            //var scheduler = new EventLoopScheduler(ts => new Thread(ts) { Name = "DataBusPoller" });

            //var query = Observable.Timer(interval, scheduler)
            //                .Select(_ => Read())
            //                .Repeat();

            //return query;
        }
        public void ScheduleAbsolute()
        {
            var  s    = new NewThreadScheduler();
            bool flag = false;

            s.Schedule(s.Now.AddMilliseconds(200), () => flag = true);
            Thread.Sleep(200);
            Assert.IsTrue(flag, "#1");
            flag = false;
            var dis = s.Schedule(s.Now.AddMilliseconds(200), () => flag = true);

            dis.Dispose();
            Thread.Sleep(200);              // make sure to wait for timer
            Assert.IsFalse(flag, "#2");
        }
Ejemplo n.º 15
0
        private static void CancellRecursive()
        {
            Action <Action> work = (Action self)//will be tranformed to loop internally
                                   =>
            {
                Console.WriteLine("Running");
                self();
            };

            var token = new NewThreadScheduler().Schedule(work);

            Console.ReadLine();
            Console.WriteLine("Cancelling");
            token.Dispose();
            Console.WriteLine("Cancelled");
        }
Ejemplo n.º 16
0
        public IObservable <long> StartConsuming(CancellationToken ct, TimeSpan gap)
        {
            var scheduler = new NewThreadScheduler(ts => new Thread(ts)
            {
                Name = "Consumer"
            });

            var obs = Observable.Generate(Read(),
                                          x => !ct.IsCancellationRequested,
                                          x => Read(),
                                          x => x,
                                          x => gap,
                                          scheduler);

            return(obs);
        }
Ejemplo n.º 17
0
        /**
         * Scheduler控制订阅和通知的发送。
         * Scheduler包含三个组件:1)一个优先队列存放任务,2)Execution context,用来决定任务在哪执行(线程池,当前线程)3)scheduler的时钟,Task是根据这个时钟调度的,不是系统时钟。
         *
         * rx中所有的Scheduler实现IScheduler接口。
         *
         */

        public static void GetSchedulers()
        {
            //立刻在当前线程上执行
            ImmediateScheduler immediate = Scheduler.Immediate;
            //在当前线程上尽可能快的执行(先放到队列中,尽快执行)
            CurrentThreadScheduler currentThreadScheduler = Scheduler.CurrentThread;
            //每次创建一个线程执行
            NewThreadScheduler newThreadScheduler = NewThreadScheduler.Default;
            //在Task Factory上执行
            TaskPoolScheduler taskPoolScheduler = TaskPoolScheduler.Default;

            //在当前Dispatcher上执行任务
            DispatcherScheduler dispatcherScheduler = DispatcherScheduler.Current;

            //在ThreadPool上执行
            ThreadPoolScheduler threadPoolScheduler = ThreadPoolScheduler.Instance;
            //默认的调度器  其原则是使用最小的并行性,for operators returning an observable with a finite and small number of messages, Rx calls Immediate.  For operators returning a potentially large or infinite number of messages, CurrentThread is called. For operators which use timers, ThreadPool is used.
            DefaultScheduler defaultScheduler = Scheduler.Default;
        }
Ejemplo n.º 18
0
        public void ExampleNewThreadSecondTask()
        {
            IScheduler scheduler = new NewThreadScheduler();

            Console.WriteLine("Starting on thread :{0}",
                              Thread.CurrentThread.ManagedThreadId);
            scheduler.Schedule("A", OuterAction);
            scheduler.Schedule("B", OuterAction);

            //Starting on thread :9
            //A start. ThreadId:10
            //A end. ThreadId:10
            //A.inner start . ThreadId:10
            //A.inner end. ThreadId:10
            //A.inner.Leaf. ThreadId:10
            //B start. ThreadId:11
            //B end. ThreadId:11
            //B.inner start . ThreadId:11
            //B.inner end. ThreadId:11
            //B.inner.Leaf. ThreadId:11
        }
Ejemplo n.º 19
0
        public Form1()
        {
            InitializeComponent();
            SynchronizationContextScheduler UIThread = new SynchronizationContextScheduler(SynchronizationContext.Current);
            NewThreadScheduler NewThread             = new NewThreadScheduler();

            //// Proxy.Connect();
            mars_font = NativeMethods.GetFontFromResource(Properties.Resources.newmars, 16.0F);

            pro1 = Observable
                   .FromAsync(() => Curiosity.GetLatestData())
                   .ObserveOn(UIThread);

            //pro2 = Observable
            //    .FromAsync(() => Curiosity.GetArchiveData());

            pro3 = Curiosity
                   .GetArchiveDataY()
                   .ToObservable()
                   .SubscribeOn(NewThread);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 使用 SubscribeOn 与 ObserveOn
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSubscribeOnObserveOn_Click(object sender, EventArgs e)
        {
            Console.WriteLine("########## 使用 SubscribeOn 与 ObserveOn :{0} ##########", Thread.CurrentThread.ManagedThreadId);

            IScheduler thread1 = new NewThreadScheduler(x => new Thread(x)
            {
                Name = "可观察对象线程"
            });
            IScheduler thread2 = new NewThreadScheduler(x => new Thread(x)
            {
                Name = "观察者线程"
            });


            var source = GetTestObservableSource();

            source
            .SubscribeOn(thread1)
            .ObserveOn(thread2)
            .Subscribe(o => Console.WriteLine("Received {2} on threadId:{0} / {1}", Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId, o),
                       () => Console.WriteLine("OnCompleted on threadId:{0} / {1}", Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId));
        }
Ejemplo n.º 21
0
        public static void DifferenceBetweenSubscribeOnAndObserveOn()
        {
            Thread.CurrentThread.Name = "Main";

            IScheduler thread1 = new NewThreadScheduler(x => new Thread(x)
            {
                Name = "Thread1"
            });
            IScheduler thread2 = new NewThreadScheduler(x => new Thread(x)
            {
                Name = "Thread2"
            });

            Observable.Create <int>(o =>
            {
                Console.WriteLine("Subscribing on " + Thread.CurrentThread.Name);
                o.OnNext(1);
                return(Disposable.Create(() => { }));
            })
            //.SubscribeOn(thread1)
            //.ObserveOn(thread2)
            .Subscribe(x => Console.WriteLine("Observing '" + x + "' on " + Thread.CurrentThread.Name));
        }
Ejemplo n.º 22
0
        private static void Cancellation()
        {
            var scheduler = new NewThreadScheduler();
            var delay     = TimeSpan.FromSeconds(1);

            Console.WriteLine("Before schedule at {0:o}", DateTime.Now);
            var token = scheduler.Schedule(delay,
                                           () => Console.WriteLine("Inside schedule at {0:o}", DateTime.Now));

            Console.WriteLine("After schedule at  {0:o}", DateTime.Now);
            token.Dispose();//remove from queue of work

            //cancel sth is running
            var list = new List <int>();

            Console.WriteLine("Enter to quit");
            var token2 = scheduler.Schedule(list, Work);

            Console.WriteLine("Press enter to cancel");
            Console.ReadLine();
            Console.WriteLine("cancelling...");
            token2.Dispose();
            Console.WriteLine("Cancelled");
        }
Ejemplo n.º 23
0
        private void StartSuck()
        {
            this.ResultLabel = string.Empty;
            if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
            {
                Thread.CurrentThread.Name = "Main";
            }

            IScheduler thread1 = new NewThreadScheduler(x => new Thread(x)
            {
                Name = "Thread1"
            });
            IScheduler thread2 = new NewThreadScheduler(x => new Thread(x)
            {
                Name = "Thread2"
            });

            var blockObs = Observable.Create((IObserver <string> observer) =>
            {
                Thread.Sleep(1000);
                observer.OnNext(string.Format("a  " + System.Threading.Thread.CurrentThread.Name));
                Thread.Sleep(1000);
                observer.OnNext(string.Format("b  " + System.Threading.Thread.CurrentThread.Name));
                observer.OnCompleted();
                Thread.Sleep(1000);
                return(Disposable.Create(() => Console.WriteLine("Observer has unsubscribed")));
            });

            blockObs
            .SubscribeOn(thread1)
            .ObserveOn(thread2).
            Subscribe((string b) =>
            {
                System.Diagnostics.Debug.WriteLine(b);
                System.Diagnostics.Debug.WriteLine("Subs: " + Thread.CurrentThread.Name + " || " + Thread.CurrentThread.ManagedThreadId);
            });

            //var obs = Observable.Create((IObserver<List<Event>> observer) =>
            //    {
            //        var result = new List<Event>();
            //        System.Diagnostics.Debug.WriteLine("Start sample task: " + Thread.CurrentThread.Name + " || " + Thread.CurrentThread.ManagedThreadId);
            //        using (HttpClient httpClient = new HttpClient())
            //        {
            //            var uri = "http://setgetgo.com/randomword/get.php";
            //            var response1 = httpClient.GetStringAsync(uri);
            //            var response2 = httpClient.GetStringAsync(uri);
            //            result.Add(new Event
            //            {
            //                AddTime = DateTime.Now,
            //                Content = response1.Result,
            //                ThreadId = Thread.CurrentThread.Name + Thread.CurrentThread.ManagedThreadId
            //            });

            //            result.Add(new Event
            //            {
            //                AddTime = DateTime.Now,
            //                Content = response2.Result,
            //                ThreadId = Thread.CurrentThread.Name + Thread.CurrentThread.ManagedThreadId
            //            });
            //        }
            //        observer.OnNext(result);
            //        observer.OnCompleted();

            //        return Disposable.Create(() => System.Diagnostics.Debug.WriteLine("Done"));
            //    });

            var obs = Observable.FromAsync(x => this.SampleTaskAsync());

            obs
            .SubscribeOn(thread2)
            .ObserveOn(DispatcherScheduler.Current)
            .Subscribe(this.HandleResponses);

            //var obs2 = this.SampleSubTask()
            //    .ToObservable()
            //    .ObserveOnDispatcher()
            //    .Subscribe(this.HandleResponse);
        }
Ejemplo n.º 24
0
 private void RunScheduleAsync(Func<Func<SchedulerOperation>, Task<int>> calculate)
 {
     Console.WriteLine("Running on thread: " + Thread.CurrentThread.ManagedThreadId);
     IObservable<int> observable = Observable.Create<int>(o =>
         {
             IDisposable d = new NewThreadScheduler().ScheduleAsync(async (scheduler, token) =>
                 {
                     o.OnNext(await calculate(scheduler.Yield));
                     o.OnCompleted();
                 });
             return Disposable.Create(() =>
                 {
                     d.Dispose();
                     Console.WriteLine("Disposed!");
                 });
         });
     Console.WriteLine("Subscribing.");
     CompositeDisposable s = new CompositeDisposable();
     for (int i = 0; i < 12; i++)
     {
         s.Add(observable.Subscribe(Console.WriteLine, () => Console.WriteLine("Completed.")));
     }
     Console.WriteLine("Subscribed.");
     Thread.Sleep(700);
     s.Dispose();
     Console.WriteLine("Should have disposed.");
     Thread.Sleep(2000);
     Console.WriteLine("Done.");
 }