Esempio n. 1
0
        public void ScheduleRelative_Cancel()
        {
            var evt = new ManualResetEvent(false);

            var id = Thread.CurrentThread.ManagedThreadId;

            var disp = DispatcherHelpers.EnsureDispatcher();
            var sch  = new DispatcherScheduler(disp);

            sch.Schedule(TimeSpan.FromSeconds(0.1), () =>
            {
                Assert.NotEqual(id, Thread.CurrentThread.ManagedThreadId);

                var d = sch.Schedule(TimeSpan.FromSeconds(0.1), () =>
                {
                    Assert.True(false);
                    evt.Set();
                });

                sch.Schedule(() =>
                {
                    d.Dispose();
                });

                sch.Schedule(TimeSpan.FromSeconds(0.2), () =>
                {
                    Assert.NotEqual(id, Thread.CurrentThread.ManagedThreadId);
                    evt.Set();
                });
            });

            evt.WaitOne();
            disp.InvokeShutdown();
        }
        private void OnLoaded(ChatClient chatClient)
        {
            var dispatcherScheduler = new DispatcherScheduler(Dispatcher);

            ObserveOnClick(SendBtn)
            .Select(_ => MessageInputBox.Text)
            .Subscribe(async text => await SendMessage(chatClient, text));

            chatClient.MessageRecieved
            .ObserveOn(dispatcherScheduler)
            .Subscribe(message => ChatBox.Items.Add(message));

            chatClient.MemberJoins
            .ObserveOn(dispatcherScheduler)
            .Subscribe(username => Members.Items.Add(username));

            chatClient.MemberDisconnects
            .ObserveOn(dispatcherScheduler)
            .Subscribe(username => Members.Items.Remove(username));

            chatClient.MembersOnline
            .ObserveOn(dispatcherScheduler)
            .Subscribe(userNames => {
                foreach (var userName in userNames)
                {
                    Members.Items.Add(userName);
                }
            });

            FromEventPattern <EventHandler, EventArgs>(e => Closed += e, e => Closed -= e)
            .Subscribe(_ => chatClient.CloseConnection());

            Task.Run(chatClient.RequestChat);
            Task.Run(chatClient.ListenAsync);
        }
Esempio n. 3
0
        public PiracContext()
        {
            if (Dispatcher.CurrentDispatcher == null)
                throw new Exception("Start should be called from within your Application.");

            UIScheduler = new DispatcherScheduler(Dispatcher.CurrentDispatcher);
        }
Esempio n. 4
0
 private IObservable <Unit> OptimizeAsync(DispatcherScheduler scheduler, IOptimizationModel optimizationModel)
 {
     return
         (from optimizationProblem in Observable.Start <OptimizationProblem>(optimizationModel.CreateProblem, scheduler)
          from unit in IterativelySolveAndUpdateAsync(optimizationProblem, optimizationModel, scheduler)
          select unit);
 }
        public void Dispatcher_Now()
        {
            var disp = EnsureDispatcher();
            var res  = new DispatcherScheduler(disp).Now - DateTime.Now;

            Assert.IsTrue(res.Seconds < 1);
        }
Esempio n. 6
0
        public PositionTracker()
        {
            dict[nameof(Trades)].Subscribe(_ =>
            {
            });
            var dispatcher = new DispatcherScheduler(this.Dispatcher);

            dict[nameof(Trades)].Where(_ => _ != null)
            .CombineLatest(dict[nameof(Date)].StartWith("Date"),
                           dict[nameof(Key)].Where(_ => _ != null).StartWith("Key"),
                           dict[nameof(Position)].Where(_ => _ != null).StartWith("Position"),
                           dict[nameof(Price)].Where(_ => _ != null).StartWith("Price"),
                           dict[nameof(Profit)].Where(_ => _ != null).StartWith("Profit"),
                           (positions, date, key, position, price, profit) => new { positions, date, key, position, price, profit })
            //
            .Subscribe(_ =>
                       GetChanges((IEnumerable)_.positions, (string)_.date, (string)_.key, (string)_.position, (string)_.price, (string)_.profit).
                       Select(t => new Trade {
                Key = t.Key, Amount = (Money)t.Value.Value["Amount"], Price = (Money)t.Value.Value["Price"], Profit = (Money)t.Value.Value["Profit"], Date = t.Value.Key
            })
                       .ToObservableChangeSet(c => c.Date + c.Key)
                       .Group(g => g.Key)
                       .Transform(t => new PositionViewModel(t))
                       .ObserveOn(dispatcher)
                       .Bind(out _data)
                       .DisposeMany()
                       .Subscribe(v =>
            {
                //this.Dispatcher.InvokeAsync(() => ListBox.ItemsSource = _data,DispatcherPriority.Background);
            }));
        }
        public void Dispatcher_ScheduleActionDue()
        {
            var id   = Thread.CurrentThread.ManagedThreadId;
            var disp = EnsureDispatcher();
            var sch  = new DispatcherScheduler(disp);
            var evt  = new ManualResetEvent(false);
            var sw   = new Stopwatch();

            sw.Start();
            sch.Schedule(() =>
            {
                sw.Stop();
                Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);
                sw.Start();
                sch.Schedule(() =>
                {
                    sw.Stop();
                    Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);
                    evt.Set();
                }, TimeSpan.FromSeconds(0.2));
            }, TimeSpan.FromSeconds(0.2));
            evt.WaitOne();
            Assert.IsTrue(sw.ElapsedMilliseconds > 380, "due " + sw.ElapsedMilliseconds);
            disp.InvokeShutdown();
        }
Esempio n. 8
0
        public void Now()
        {
            var disp = DispatcherHelpers.EnsureDispatcher();
            var res  = new DispatcherScheduler(disp).Now - DateTime.Now;

            Assert.True(res.Seconds < 1);
        }
Esempio n. 9
0
        private void OnLoaded(EventPattern <RoutedEventArgs> eventPattern)
        {
            var dispatcherScheduler = new DispatcherScheduler(Dispatcher);
            var client = new ChatClient();

            ObserveOnClick(ConnectBtn)
            .Where(AddressIsValid)
            .Where(PortIsValid)
            .SelectMany(_ =>
                        client.TryConnectAsync(new IPEndPoint(IPAddress.Parse(Address.Text), int.Parse(Port.Text)))
                        )
            .ObserveOn(dispatcherScheduler)
            .Subscribe(OnConnectAttempt);

            ObserveOnClick(RegisterBtn)
            .SelectMany(_ => client.RegisterAsync(UserNameBox.Text)) // Consumes the task
            .ObserveOn(dispatcherScheduler)                          // Use the dispatcher for the following UI updates.
            .Subscribe(successfulRegister => {
                if (successfulRegister)
                {
                    ProceedToMainWindow(client);
                }
                else
                {
                    Label.Text = $"{UserNameBox.Text} is taken, try with a different name";
                }
            });
        }
Esempio n. 10
0
 public void Now()
 {
     using (DispatcherHelpers.RunTest(out var disp))
     {
         var res = new DispatcherScheduler(disp).Now - DateTime.Now;
         Assert.True(res.Seconds < 1);
     }
 }
Esempio n. 11
0
 public WindowsPhoneSchedulers(DispatcherScheduler dispatcher)
 {
     if (dispatcher == null)
     {
         throw new ArgumentNullException("dispatcher");
     }
     _dispatcher = dispatcher;
 }
Esempio n. 12
0
 static DataFlowProcessors()
 {
     GalaSoft.MvvmLight.Threading.DispatcherHelper.Initialize();
     ReactiveUI.RxApp.MainThreadScheduler.Schedule(() => {
         _DispatcherTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
         _UIDispatcherScheduler   = DispatcherScheduler.Current;
     });
 }
Esempio n. 13
0
 public void Schedule_ArgumentChecking()
 {
     var disp = DispatcherHelpers.EnsureDispatcher();
     var s = new DispatcherScheduler(disp);
     ReactiveAssert.Throws<ArgumentNullException>(() => s.Schedule(42, default(Func<IScheduler, int, IDisposable>)));
     ReactiveAssert.Throws<ArgumentNullException>(() => s.Schedule(42, TimeSpan.FromSeconds(1), default(Func<IScheduler, int, IDisposable>)));
     ReactiveAssert.Throws<ArgumentNullException>(() => s.Schedule(42, DateTimeOffset.Now, default(Func<IScheduler, int, IDisposable>)));
 }
Esempio n. 14
0
        public void SchedulePeriodic_ArgumentChecking()
        {
            var disp = DispatcherHelpers.EnsureDispatcher();
            var s    = new DispatcherScheduler(disp);

            ReactiveAssert.Throws <ArgumentNullException>(() => s.SchedulePeriodic(42, TimeSpan.FromSeconds(1), default(Func <int, int>)));
            ReactiveAssert.Throws <ArgumentOutOfRangeException>(() => s.SchedulePeriodic(42, TimeSpan.FromSeconds(-1), x => x));
        }
Esempio n. 15
0
        public void Schedule_ArgumentChecking()
        {
            var disp = DispatcherHelpers.EnsureDispatcher();
            var s    = new DispatcherScheduler(disp);

            ReactiveAssert.Throws <ArgumentNullException>(() => s.Schedule(42, default(Func <IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws <ArgumentNullException>(() => s.Schedule(42, TimeSpan.FromSeconds(1), default(Func <IScheduler, int, IDisposable>)));
            ReactiveAssert.Throws <ArgumentNullException>(() => s.Schedule(42, DateTimeOffset.Now, default(Func <IScheduler, int, IDisposable>)));
        }
Esempio n. 16
0
        public IObservable <Unit> RecalculateAsync()
        {
            var dispatcher = Dispatcher.FromThread(Thread.CurrentThread);
            var scheduler  = new DispatcherScheduler(dispatcher);

            return(from unit1 in OptimizeAsync(scheduler, wholeShapeOptimizationModel)
                   from unit2 in NotifySnapCompleteAsync(scheduler)
                   select unit2);
        }
Esempio n. 17
0
        public PiracContext()
        {
            if (Dispatcher.CurrentDispatcher == null)
            {
                throw new Exception("Start should be called from within your Application.");
            }

            MainScheduler = new DispatcherScheduler(Dispatcher.CurrentDispatcher);
        }
Esempio n. 18
0
	    public WpfSchedulers(DispatcherScheduler dispatcher, IPriorityScheduler priorityDispatcher, IPriorityScheduler threadPool)
	    {
			if (dispatcher == null) throw new ArgumentNullException("dispatcher");
			if (priorityDispatcher == null) throw new ArgumentNullException("priorityDispatcher");
			if (threadPool == null) throw new ArgumentNullException("threadPool");
			_dispatcher = dispatcher;
			_threadPool = threadPool;
			_priorityDispatcher = priorityDispatcher;
	    }
Esempio n. 19
0
        static void Main()
        {
            // UI scheduler.
            IScheduler mainScheduler = new DispatcherScheduler(Dispatcher.CurrentDispatcher);

            IBootstrapping boot = new Bootstrapping(mainScheduler);

            boot.Startup();
            boot.Dispose();
        }
 public SmallDataSet()
 {
     var evls = new EventLoopScheduler();
     var ds = new DispatcherScheduler(Dispatcher);
     var myStuff = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
     //var folder = new FolderNode(@"C:\Users\Lee\Documents\\", evls, ds);
     var folder = new FolderNode(myStuff, evls, ds);
     InitializeComponent();
     DataContext = folder;
 }
Esempio n. 21
0
 public Schedulers(Dispatcher mainThreadDispatcher)
 {
     if (mainThreadDispatcher == null)
     {
         throw new ArgumentNullException(nameof(mainThreadDispatcher));
     }
     MainThread = new DispatcherScheduler(mainThreadDispatcher);
     Background = new EventLoopScheduler();
     ThreadPool = ThreadPoolScheduler.Instance;
 }
Esempio n. 22
0
 public static void SetupRxMvvmConfiguration(Application application)
 {
     RxMvvmConfiguration.SetIsInDesignModeFunc(
         () =>
             {
                 Window firstWindow = application.Windows.Count > 0 ? application.Windows[0] : null;
                 return firstWindow != null && DesignerProperties.GetIsInDesignMode(firstWindow);
             });
     IScheduler scheduler = new DispatcherScheduler(application.Dispatcher);
     RxMvvmConfiguration.SetNotifyPropertyChangedSchedulerFactory(() => scheduler);
 }
Esempio n. 23
0
        public void Dispatcher_ScheduleAction()
        {
            var id   = Thread.CurrentThread.ManagedThreadId;
            var disp = EnsureDispatcher();
            var sch  = new DispatcherScheduler(disp);
            var evt  = new ManualResetEvent(false);

            sch.Schedule(() => { Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId); evt.Set(); });
            evt.WaitOne();
            disp.InvokeShutdown();
        }
Esempio n. 24
0
 public void Schedule()
 {
     using (DispatcherHelpers.RunTest(out var disp))
     {
         RunAsync(evt =>
         {
             var id  = Thread.CurrentThread.ManagedThreadId;
             var sch = new DispatcherScheduler(disp);
             sch.Schedule(() =>
             {
                 Assert.NotEqual(id, Thread.CurrentThread.ManagedThreadId);
                 evt.Set();
             });
         });
     }
 }
Esempio n. 25
0
        private void target_Click(object sender, RoutedEventArgs e)
        {
            _messageDialogService.Show(Message);

            return;

            var ds = new DispatcherScheduler(Application.Current.Dispatcher, DispatcherPriority.Render);

            Observable.Start(() =>
            {
                _messageDialogService.Show(Message);
            },
                             ds);     //DispatcherScheduler.Current

            //            e.Handled = false;
        }
Esempio n. 26
0
        public void Schedule()
        {
            var disp = DispatcherHelpers.EnsureDispatcher();

            RunAsync(evt =>
            {
                var id  = Thread.CurrentThread.ManagedThreadId;
                var sch = new DispatcherScheduler(disp);
                sch.Schedule(() =>
                {
                    Assert.NotEqual(id, Thread.CurrentThread.ManagedThreadId);
                    disp.InvokeShutdown();
                    evt.Set();
                });
            });
        }
Esempio n. 27
0
        /// <summary>
        /// Initialises a new instance of the <see cref="WindowBase"/> class.
        /// </summary>
        public WindowBase()
        {
            DispatcherScheduler scheduler = new DispatcherScheduler(this.Dispatcher);
            var locationChanges           = Observable.FromEventPattern <EventHandler, EventArgs>(
                h => LocationChanged += h,
                h => LocationChanged -= h);
            var sizeChanges = Observable.FromEventPattern <SizeChangedEventHandler, SizeChangedEventArgs>(
                h => SizeChanged += h,
                h => SizeChanged -= h);
            var merged = Observable.Merge(
                sizeChanges.Select(_ => Unit.Default),
                locationChanges.Select(_ => Unit.Default));

            merged
            .Throttle(TimeSpan.FromSeconds(5), scheduler)
            .Subscribe(_ => this.UpdateWindowPlacement());
        }
Esempio n. 28
0
 public WpfSchedulers(DispatcherScheduler dispatcher, IPriorityScheduler priorityDispatcher, IPriorityScheduler threadPool)
 {
     if (dispatcher == null)
     {
         throw new ArgumentNullException("dispatcher");
     }
     if (priorityDispatcher == null)
     {
         throw new ArgumentNullException("priorityDispatcher");
     }
     if (threadPool == null)
     {
         throw new ArgumentNullException("threadPool");
     }
     _dispatcher         = dispatcher;
     _threadPool         = threadPool;
     _priorityDispatcher = priorityDispatcher;
 }
        private void DoSetApplicationUiScheduler()
        {
            var dispatcher = Dispatcher.FromThread(Thread.CurrentThread); //7:30

            if (dispatcher == null)
            {
                throw new InvalidOperationException("Current thread of execution does not have an associated dispatcher. This method must be called from the application IU thread.");
            }

            _uiTaskScheduler       = TaskScheduler.FromCurrentSynchronizationContext();
            _uiDispatcherScheduler = DispatcherScheduler.Current;

            if (_uiTaskScheduler == null ||
                _uiDispatcherScheduler == null)
            {
                throw new InvalidOperationException($"Application UI TaskScheduler and DispatcherScheduler could not been set. Call {nameof(SetApplicationUiScheduler)} from the UI thread to capture this context.");
            }
        }
Esempio n. 30
0
        public HostNode(
            GroupedConnection groupedConnection,
            IManagementActionsController managementActionsController,
            IExplicitConnectionCache explicitConnectionCache,
            IImplicitConnectionCache implicitConnectionCache,
            DispatcherScheduler dispatcherScheduler
            )
        {
            if (groupedConnection == null)
            {
                throw new ArgumentNullException(nameof(groupedConnection));
            }
            if (managementActionsController == null)
            {
                throw new ArgumentNullException(nameof(managementActionsController));
            }
            if (groupedConnection.Key.Level != GroupedConnectionKeyLevel.AuthorisationKey)
            {
                throw new ArgumentException($"Expected key level of {GroupedConnectionKeyLevel.AuthorisationKey}.", nameof(groupedConnection));
            }

            Host             = groupedConnection[GroupedConnectionKeyLevel.Host];
            AuthorisationKey = groupedConnection[GroupedConnectionKeyLevel.AuthorisationKey];
            var authKeyHint = AuthorisationKey ?? "";

            AuthorisationKeyHint =
                (authKeyHint.Length > 0 ? authKeyHint.Substring(0, Math.Min(authKeyHint.Length, 5)) : "")
                + "...";

            CreateDatabaseCommand = new Command(_ => managementActionsController.AddDatabase(this));

            ReadOnlyObservableCollection <DatabaseNode> nodes;

            _disposable = explicitConnectionCache.BuildChildNodes(
                implicitConnectionCache,
                groupedConnection.Key,
                GroupedConnectionKeyLevel.DatabaseId,
                groupedCn =>
                new DatabaseNode(this, groupedCn, managementActionsController, explicitConnectionCache,
                                 implicitConnectionCache, dispatcherScheduler),
                DatabaseSortComparer,
                dispatcherScheduler, out nodes);
            Databases = nodes;
        }
Esempio n. 31
0
        public void Test1()
        {
            // VisualStudioがあればスナップ対象にする
            var q1 = from p in Process.GetProcesses()
                     let Name = p.ProcessName
                     let IsWindow = (p.MainWindowHandle != IntPtr.Zero)
                     let WinName = p.MainWindowTitle
                     let HWND = p.MainWindowHandle
                     where HWND != IntPtr.Zero && Name == "devenv"
                     select new { Process = p, Name, IsWindow, WinName, HWND };
            var vs = q1.FirstOrDefault();

            try {
                if (vs != null) { Blue.Windows.StickyWindowWPF.Register(vs.HWND); }

                // ウィンドウの起動
                var mylock = new object();
                DispatcherScheduler sc = null;
                var t = new Thread(() =>
                {
                    sc = new DispatcherScheduler(Dispatcher.CurrentDispatcher);
                    lock (mylock) Monitor.PulseAll(mylock);
                    Dispatcher.Run();
                });
                t.SetApartmentState(ApartmentState.STA);
                t.IsBackground = true;
                lock (mylock) {
                    t.Start();
                    Monitor.Wait(mylock);
                }
                Observable.Start(() =>
                {
                    var win = new VTreeViewTestWindow();
                    win.ShowDialog();
                    sc.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
                    return Unit.Default;
                }, sc);
                t.Join();
            }
            finally {
                if (vs != null) { Blue.Windows.StickyWindowWPF.Unregister(vs.HWND); }
            }
        }
        /**
         * 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;
        }
Esempio n. 33
0
        public void Dispatcher_ScheduleActionError()
        {
            var ex = new Exception();

            var id   = Thread.CurrentThread.ManagedThreadId;
            var disp = EnsureDispatcher();
            var evt  = new ManualResetEvent(false);

            disp.UnhandledException += (o, e) =>
            {
                Assert.AreSame(ex, e.Exception.InnerException); // CHECK
                evt.Set();
                e.Handled = true;
            };
            var sch = new DispatcherScheduler(disp);

            sch.Schedule(() => { throw ex; });
            evt.WaitOne();
            disp.InvokeShutdown();
        }
Esempio n. 34
0
        public void Schedule()
        {
            var disp = DispatcherHelpers.EnsureDispatcher();

            RunAsync(evt =>
            {
                var id  = Thread.CurrentThread.ManagedThreadId;
                var sch = new DispatcherScheduler(disp);
                sch.Schedule(() =>
                {
#if SILVERLIGHT
                    Assert.Equal(id, Thread.CurrentThread.ManagedThreadId); // Single-threaded test framework
#else
                    Assert.NotEqual(id, Thread.CurrentThread.ManagedThreadId);
#endif
                    disp.InvokeShutdown();
                    evt.Set();
                });
            });
        }
Esempio n. 35
0
        /// <summary>
        /// Initialises a new instance of the <see cref="WindowBase"/> class.
        /// </summary>
        public WindowBase()
        {
            DispatcherScheduler scheduler = new DispatcherScheduler(this.Dispatcher);
            var locationChanges           = Observable.FromEventPattern <EventHandler, EventArgs>(
                h => LocationChanged += h,
                h => LocationChanged -= h);
            var sizeChanges = Observable.FromEventPattern <SizeChangedEventHandler, SizeChangedEventArgs>(
                h => SizeChanged += h,
                h => SizeChanged -= h);
            var merged = Observable.Merge(
                sizeChanges.Select(_ => Unit.Default),
                locationChanges.Select(_ => Unit.Default));

            merged
            .Throttle(TimeSpan.FromSeconds(5), scheduler)
            .Subscribe(_ => this.UpdateWindowPlacement());

            DependencyPropertyDescriptor
            .FromProperty(ApplicationBarProperty, typeof(Elysium.Controls.Window))
            .AddValueChanged(this, OnApplicationBarChanged);
        }
Esempio n. 36
0
        public ListBoxEx(Func <object, object> _keyfunc)
        {
            Uri resourceLocater = new Uri("/UtilityWpf.View;component/Themes/ListBoxEx.xaml", System.UriKind.Relative);
            ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater);

            Style = resourceDictionary["ListBoxExStyle"] as Style;

            UI = new System.Reactive.Concurrency.DispatcherScheduler(Application.Current.Dispatcher);

            //_.GetType().GetProperty("Object").GetValue(_)
            interactivecollection = ViewModel.InteractiveCollectionFactory.Build(
                _ => _keyfunc(_),//UtilityHelper.PropertyHelper.GetPropValue<object>(_,"Object")),
                ItemsSourceSubject.Select(v => v.Cast <object>()),
                FilterSubject,
                DeletedSubject.WithLatestFrom(RemoveSubject.StartWith(Remove).DistinctUntilChanged(), (d, r) => r ? d : null).Where(v => v != null),
                ClearedSubject,
                UI, null, IsReadOnly
                );
            CollectionChanged();

            Init();
        }
 public void Now()
 {
     var disp = DispatcherHelpers.EnsureDispatcher();
     var res = new DispatcherScheduler(disp).Now - DateTime.Now;
     Assert.IsTrue(res.Seconds < 1);
 }
        public void SchedulePeriodic()
        {
            var evt = new ManualResetEvent(false);

            var id = Thread.CurrentThread.ManagedThreadId;

            var disp = DispatcherHelpers.EnsureDispatcher();
            var sch = new DispatcherScheduler(disp);

            var d = new SingleAssignmentDisposable();

            d.Disposable = sch.SchedulePeriodic(1, TimeSpan.FromSeconds(0.1), n =>
            {
                Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);

                if (n == 3)
                {
                    d.Dispose();

                    sch.Schedule(TimeSpan.FromSeconds(0.2), () =>
                    {
                        Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);
                        evt.Set();
                    });
                }

                if (n > 3)
                {
                    Assert.Fail();
                }

                return n + 1;
            });

            evt.WaitOne();
            disp.InvokeShutdown();
        }
        public void SchedulePeriodic_ArgumentChecking()
        {
            var disp = DispatcherHelpers.EnsureDispatcher();
            var s = new DispatcherScheduler(disp);

            ReactiveAssert.Throws<ArgumentNullException>(() => s.SchedulePeriodic(42, TimeSpan.FromSeconds(1), default(Func<int, int>)));
            ReactiveAssert.Throws<ArgumentOutOfRangeException>(() => s.SchedulePeriodic(42, TimeSpan.FromSeconds(-1), x => x));
        }
        public void ScheduleRelative_Cancel()
        {
            var evt = new ManualResetEvent(false);
            
            var id = Thread.CurrentThread.ManagedThreadId;

            var disp = DispatcherHelpers.EnsureDispatcher();
            var sch = new DispatcherScheduler(disp);
            
            sch.Schedule(TimeSpan.FromSeconds(0.1), () =>
            {
                Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);

                var d = sch.Schedule(TimeSpan.FromSeconds(0.1), () =>
                {
                    Assert.Fail();
                    evt.Set();
                });

                sch.Schedule(() =>
                {
                    d.Dispose();
                });

                sch.Schedule(TimeSpan.FromSeconds(0.2), () =>
                {
                    Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);
                    evt.Set();
                });
            });

            evt.WaitOne();
            disp.InvokeShutdown();
        }
        private void ScheduleRelative_(TimeSpan delay)
        {
            var evt = new ManualResetEvent(false);

            var id = Thread.CurrentThread.ManagedThreadId;

            var disp = DispatcherHelpers.EnsureDispatcher();
            var sch = new DispatcherScheduler(disp);

            sch.Schedule(delay, () =>
            {
                Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);

                sch.Schedule(delay, () =>
                {
                    Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);
                    evt.Set();
                });
            });

            evt.WaitOne();
            disp.InvokeShutdown();
        }
        public void ScheduleError()
        {
            var ex = new Exception();

            var id = Thread.CurrentThread.ManagedThreadId;
            var disp = DispatcherHelpers.EnsureDispatcher();
            var evt = new ManualResetEvent(false);
            disp.UnhandledException += (o, e) =>
            {
#if DESKTOPCLR40 || DESKTOPCLR45
                Assert.AreSame(ex, e.Exception); // CHECK
#else
                Assert.AreSame(ex, e.Exception.InnerException); // CHECK
#endif
                evt.Set();
                e.Handled = true;
            };
            var sch = new DispatcherScheduler(disp);
            sch.Schedule(() => { throw ex; });
            evt.WaitOne();
            disp.InvokeShutdown();
        }
Esempio n. 43
0
 /// <summary>
 /// Initialises a new instance of the <see cref="WindowBase"/> class.
 /// </summary>
 public WindowBase()
 {
     DispatcherScheduler scheduler = new DispatcherScheduler(this.Dispatcher);
     var locationChanges = Observable.FromEventPattern<EventHandler, EventArgs>(
         h => LocationChanged += h,
         h => LocationChanged -= h);
     var sizeChanges = Observable.FromEventPattern<SizeChangedEventHandler, SizeChangedEventArgs>(
         h => SizeChanged += h,
         h => SizeChanged -= h);
     var merged = Observable.Merge(
         sizeChanges.Select(_ => Unit.Default),
         locationChanges.Select(_ => Unit.Default));
     merged
         .Throttle(TimeSpan.FromSeconds(5), scheduler)
         .Subscribe(_ => this.UpdateWindowPlacement());
 }
Esempio n. 44
0
 public SchedulerProvider(Dispatcher dispatcher)
 {
     Dispatcher = new DispatcherScheduler(dispatcher);
 }
        public void Schedule()
        {
            var disp = DispatcherHelpers.EnsureDispatcher();

            RunAsync(evt =>
            {
                var id = Thread.CurrentThread.ManagedThreadId;
                var sch = new DispatcherScheduler(disp);
                sch.Schedule(() =>
                {
#if SILVERLIGHT
                    Assert.AreEqual(id, Thread.CurrentThread.ManagedThreadId); // Single-threaded test framework
#else
                    Assert.AreNotEqual(id, Thread.CurrentThread.ManagedThreadId);
#endif
                    disp.InvokeShutdown();
                    evt.Set();
                });
            });
        }
 public SchedulerProvider(Dispatcher dispatcher)
 {
     MainThread = new DispatcherScheduler(dispatcher);
     Background = TaskPoolScheduler.Default;
 }
Esempio n. 47
0
		public WindowsPhoneSchedulers(DispatcherScheduler dispatcher)
		{
			if (dispatcher == null) throw new ArgumentNullException("dispatcher");
			_dispatcher = dispatcher;
		}
Esempio n. 48
0
		public static IViewPresenter Create(Func<FrameworkElement, IDisposable> showView){
			var scheduler = new DispatcherScheduler(Application.Current.Dispatcher);
			return new DelegatePresenter(showView, scheduler);
		}
Esempio n. 49
0
		public static IViewPresenter Defer(Func<IViewPresenter> factory) {
			var scheduler = new DispatcherScheduler(Application.Current.Dispatcher);
			return new DelegatePresenter(view => factory().ShowView(view), scheduler);
		}
Esempio n. 50
0
        /// <summary>
        /// Initialises a new instance of the <see cref="WindowBase"/> class.
        /// </summary>
        public WindowBase()
        {
            DispatcherScheduler scheduler = new DispatcherScheduler(this.Dispatcher);
            var locationChanges = Observable.FromEventPattern<EventHandler, EventArgs>(
                h => LocationChanged += h,
                h => LocationChanged -= h);
            var sizeChanges = Observable.FromEventPattern<SizeChangedEventHandler, SizeChangedEventArgs>(
                h => SizeChanged += h,
                h => SizeChanged -= h);
            var merged = Observable.Merge(
                sizeChanges.Select(_ => Unit.Default),
                locationChanges.Select(_ => Unit.Default));
            merged
                .Throttle(TimeSpan.FromSeconds(5), scheduler)
                .Subscribe(_ => this.UpdateWindowPlacement());

            DependencyPropertyDescriptor
                .FromProperty(ApplicationBarProperty, typeof(Elysium.Controls.Window))
                .AddValueChanged(this, OnApplicationBarChanged);
        }
Esempio n. 51
0
 public SchedulerProvider(Dispatcher dispatcher)
 {
     MainThread = new DispatcherScheduler(dispatcher);
 }
 public SchedulerProvider()
 {
     _dispatcherScheduler = DispatcherScheduler.Current;
 }