示例#1
0
                protected void ScheduleDrain()
                {
                    var cd = new CancellationDisposable();

                    _cancelable.Disposable = cd;

                    _scheduler.AsLongRunning() !.ScheduleLongRunning(cd.Token, DrainQueue); // NB: This class is only used with long-running schedulers.
                }
        protected DisposableAsyncObject(IScheduler scheduler)
        {
            Scheduler   = scheduler;
            Disposables = new CompositeDisposable();

            m_tokenSource = new CancellationDisposable();
            DisposedToken = m_tokenSource.Token;
        }
示例#3
0
文件: Image.cs 项目: wiltonlazary/uno
        private void Execute(Func <CancellationToken, Task> handler)
        {
            var cd = new CancellationDisposable();

            var dummy = handler(cd.Token);

            _imageFetchDisposable.Disposable = cd;
        }
示例#4
0
        private async Task CalibrateAsync(ICalibrator calibrator)
        {
            var execution = calibrator as IEyeTrackerCalibrationExecution;

            var result = SessionStepResult.Failed;

            using (var cancellation = new CancellationDisposable())
            {
                _cancellation = cancellation;

                try
                {
                    execution.CalibrationFinished += Execution_CalibrationFinished;

                    await AsyncHelper.InvokeAsync <CalibratorStateChangedEventHandler, bool>
                    (
                        () => { },
                        h => calibrator.StateChanged += h,
                        h => calibrator.StateChanged -= h,
                        tcs => (c, state) =>
                    {
                        switch (state)
                        {
                        case CalibratorState.Canceled:
                            tcs.TrySetResult(false);
                            break;

                        case CalibratorState.Completed:
                            tcs.TrySetResult(true);
                            break;
                        }
                    },
                        cancellation.Token
                    );

                    // create result with calibrations
                    result = new EyeTrackerCalibrationSessionStepResult(_calibrations);
                }
                catch (OperationCanceledException)
                {
                    await calibrator.CancelAsync();
                }
                finally
                {
                    //remove handler from execution
                    if (execution != null)
                    {
                        execution.CalibrationFinished -= Execution_CalibrationFinished;
                    }
                }

                Navigation.Clear();

                _cancellation = null;
            }

            OnCompleted(result);
        }
        /// <summary>
        /// Instantiates the <see cref="ProgressDialog"/>.
        /// </summary>
        /// <param name="title">The title.</param>
        /// <param name="message">The message.</param>
        public ProgressDialog(string title, string message)
        {
            InitializeComponent();

            Heading = title;
            Message = message;

            _cancellationDisposable = new CancellationDisposable();
        }
示例#6
0
 void Test3()
 {
     using (var cancellation = new CancellationDisposable())
     {
         CancellationToken token = cancellation.Token;
         // Pass the token to methods that respond to it.
     }
     // At this point, the token is canceled.
 }
        public override long RunPass()
        {
            var ob = Observable.Create <long>(o =>
            {
                var cancel = new CancellationDisposable();  // internally creates a new CancellationTokenSource
                Scheduler.Default.Schedule(() =>
                {
                    for (long i = 0; i < Iterations; i++)
                    {
                        //Thread.Sleep(200);  // here we do the long lasting background operation
                        if (!cancel.Token.IsCancellationRequested)     // check cancel token periodically
                        {
                            o.OnNext(i++);
                        }
                        else
                        {
                            Console.WriteLine("Aborting because cancel event was signaled!");
                            o.OnCompleted();
                            return;
                        }
                    }
                }
                                           );

                return(cancel);
            }
                                              );

            _disruptor.Start();

            var sw           = Stopwatch.StartNew();
            var subscription = ob.Subscribe(i =>
            {
                var sequence = _ringBuffer.Next();
                _ringBuffer[sequence].Value = i;
                _ringBuffer.Publish(sequence);
            });

            //这里取消任务
            //subscription.Dispose();
            //for (long i = 0; i < Iterations; i++)
            //{
            //    var sequence = _ringBuffer.Next();
            //    _ringBuffer[sequence].Value = i;
            //    _ringBuffer.Publish(sequence);
            //}

            _mru.WaitOne();

            var opsPerSecond = (Iterations * 1000L) / sw.ElapsedMilliseconds;

            _disruptor.Shutdown();

            Assert.AreEqual(ExpectedResult, _fizzBuzzEventHandler.FizzBuzzCounter);

            return(opsPerSecond);
        }
示例#8
0
        protected override void Main()
        {
            if (Environment.OSVersion.Version < new Version(6, 2))
            {
                TraceError(Text.LabRequiresWindows8OrHigher);
                return;
            }

            const int port        = 5494;
            string    subProtocol = GetType().Name;

            var userMessages = new BehaviorSubject <string>(null);

            var client = new ClientWebSocket();

            client.Options.AddSubProtocol(subProtocol);

            using (client)
                using (var cancel = new CancellationDisposable())
                    using (ObservableHttpListener
                           .StartWebSockets(new IPEndPoint(IPAddress.Loopback, port), subProtocol)
                           .Subscribe(
                               async request =>
                    {
                        using (var socket = request.WebSocket)
                        {
                            try
                            {
                                var message = await ReceiveMessageAsync(socket, cancel.Token);
                                await SendMessageAsync("You sent \"" + message + "\"", socket, cancel.Token);
                                await ReceiveCloseMessageAsync(socket, cancel.Token);
                            }
                            catch (OperationCanceledException)
                            {
                            }
                        }
                    },
                               TraceError))
                        using ((from _ in client.ConnectAsync(new Uri("ws://localhost:" + port), cancel.Token).ToObservable()
                                .Do(_ => TraceLine(Environment.NewLine + "(Connected to host on sub-protocol \"{0}\")", client.SubProtocol))
                                from message in userMessages.Where(m => m != null).Take(1)
                                from __ in SendMessageAsync(message, client, cancel.Token).ToObservable()
                                from response in ReceiveMessageAsync(client, cancel.Token).ToObservable()
                                .Do(___ => client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", cancel.Token))
                                select response)
                               .Subscribe(
                                   response => TraceLine("Response: {0}", response),
                                   TraceError,
                                   () => TraceLine("{0}: {1}", Text.Client, Text.Done)))
                        {
                            userMessages.OnNext(UserInput("{0}> ", Instructions.EnterAMessage));

                            TraceStatus(Instructions.PressAnyKeyToCancel);

                            WaitForKey();
                        }
        }
示例#9
0
        public static void CancelDisposable_HasACancellationToken_ThatWillBeCancelled_WhenTheDisposableIsDisposed()
        {
            var cancellationDisposable = new CancellationDisposable();

            cancellationDisposable.Token.Register(() => Console.WriteLine("Disposed from cancellation token"));

            Console.WriteLine("Disposing");
            cancellationDisposable.Dispose();
        }
示例#10
0
        private async void RefreshImageAsync(Windows.Foundation.Rect drawRect)
        {
            CoreDispatcher.CheckThreadAccess();

            var cd = new CancellationDisposable();

            _refreshPaint.Disposable = cd;

            await RefreshImage(cd.Token, drawRect);
        }
示例#11
0
        public void CancellationDisposable_DefaultCtor()
        {
            var c = new CancellationDisposable();

            Assert.IsNotNull(c.Token);
            Assert.IsFalse(c.Token.IsCancellationRequested);
            Assert.IsTrue(c.Token.CanBeCanceled);
            c.Dispose();
            Assert.IsTrue(c.Token.IsCancellationRequested);
        }
            protected override IDisposable SubscribeCore(IObserver <TResult> observer)
            {
                var cancellable = new CancellationDisposable();

                var taskObservable         = subscribeAsync(observer, cancellable.Token).ToObservable();
                var taskCompletionObserver = new TaskCompletionObserver(observer);
                var subscription           = taskObservable.Subscribe(taskCompletionObserver);

                return(StableCompositeDisposable.Create(cancellable, subscription));
            }
示例#13
0
        /// <inheritdoc/>
        public override IDisposable Schedule <TState>(TState state, TimeSpan dueTime, Func <IScheduler, TState, IDisposable> action)
        {
            IDisposable PostOnDispatcher()
            {
                var composite = new CompositeDisposable(2);

                var cancellation = new CancellationDisposable();

                Dispatcher.UIThread.Post(() =>
                {
                    if (!cancellation.Token.IsCancellationRequested)
                    {
                        composite.Add(action(this, state));
                    }
                }, DispatcherPriority.Background);

                composite.Add(cancellation);

                return(composite);
            }

            if (dueTime == TimeSpan.Zero)
            {
                if (!Dispatcher.UIThread.CheckAccess())
                {
                    return(PostOnDispatcher());
                }
                else
                {
                    if (_reentrancyGuard >= MaxReentrantSchedules)
                    {
                        return(PostOnDispatcher());
                    }

                    try
                    {
                        _reentrancyGuard++;

                        return(action(this, state));
                    }
                    finally
                    {
                        _reentrancyGuard--;
                    }
                }
            }
            else
            {
                var composite = new CompositeDisposable(2);

                composite.Add(DispatcherTimer.RunOnce(() => composite.Add(action(this, state)), dueTime));

                return(composite);
            }
        }
示例#14
0
        /// <summary>
        /// Schedules a periodic piece of work by running a platform-specific timer to create tasks periodically.
        /// </summary>
        /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
        /// <param name="state">Initial state passed to the action upon the first iteration.</param>
        /// <param name="period">Period for running the work periodically.</param>
        /// <param name="action">Action to be executed, potentially updating the state.</param>
        /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
        /// <exception cref="ArgumentNullException"><paramref name="action"/> is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than TimeSpan.Zero.</exception>
        public IDisposable SchedulePeriodic <TState>(TState state, TimeSpan period, Func <TState, TState> action)
        {
            if (period < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException("period");
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

#if !NO_TASK_DELAY
            var cancel = new CancellationDisposable();

            var state1 = state;
            var gate   = new AsyncLock();

            var moveNext = default(Action);
            moveNext = () =>
            {
                Task.Delay(period, cancel.Token).ContinueWith(
                    _ =>
                {
                    moveNext();

                    gate.Wait(() =>
                    {
                        state1 = action(state1);
                    });
                },
                    CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, taskFactory.Scheduler
                    );
            };

            moveNext();

            return(new CompositeDisposable(cancel, gate));
#else
            var state1 = state;
            var gate   = new AsyncLock();

            var timer = ConcurrencyAbstractionLayer.Current.StartPeriodicTimer(() =>
            {
                taskFactory.StartNew(() =>
                {
                    gate.Wait(() =>
                    {
                        state1 = action(state1);
                    });
                });
            }, period);

            return(new CompositeDisposable(timer, gate));
#endif
        }
示例#15
0
文件: Image.cs 项目: zzyzy/uno
        private void Dispatch(Func <CancellationToken, Task> handler)
        {
            var cd = new CancellationDisposable();

            Dispatcher.RunAsync(
                Core.CoreDispatcherPriority.Normal,
                () => handler(cd.Token)
                ).AsTask(cd.Token);

            _imageFetchDisposable.Disposable = cd;
        }
        protected override void UpdateOptions(Loadzup.Options options)
        {
            var cancellationToken = new CancellationDisposable();

            _gameObject
            .OnDestroyAsObservable()
            .Take(1)
            .Subscribe(_ => cancellationToken.Dispose());

            options.CancellationToken = cancellationToken;
        }
示例#17
0
        public void CancellationDisposable_TokenCtor()
        {
            var t = new CancellationTokenSource();
            var c = new CancellationDisposable(t);

            Assert.IsTrue(t.Token == c.Token);
            Assert.IsFalse(c.Token.IsCancellationRequested);
            Assert.IsTrue(c.Token.CanBeCanceled);
            c.Dispose();
            Assert.IsTrue(c.Token.IsCancellationRequested);
        }
        /// <summary>
        /// Instantiates the <see cref="ProgressDialog"/>.
        /// </summary>
        /// <param name="title">The title.</param>
        /// <param name="message">The message.</param>
        public ProgressDialog(string title, string message)
        {
            Heading = title;
            Message = message;

            InitializeComponent();

            DataContext = this;

            _cancellationDisposable = new CancellationDisposable();
        }
        /// <summary>
        /// Schedules a periodic piece of work by running a platform-specific timer to create tasks periodically.
        /// </summary>
        /// <typeparam name="TState">The type of the state passed to the scheduled action.</typeparam>
        /// <param name="state">Initial state passed to the action upon the first iteration.</param>
        /// <param name="period">Period for running the work periodically.</param>
        /// <param name="action">Action to be executed, potentially updating the state.</param>
        /// <returns>The disposable object used to cancel the scheduled recurring action (best effort).</returns>
        /// <exception cref="ArgumentNullException"><paramref name="action"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="period"/> is less than <see cref="TimeSpan.Zero"/>.</exception>
        public IDisposable SchedulePeriodic <TState>(TState state, TimeSpan period, Func <TState, TState> action)
        {
            if (period < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(period));
            }
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            var cancel = new CancellationDisposable();

            var state1 = state;
            var gate   = new AsyncLock();

            var moveNext = default(Action);

            moveNext = () =>
            {
                //TaskHelpers.Delay(period, cancel.Token).ContinueWith(
                //    _ =>
                //    {
                //        moveNext();

                //        gate.Wait(() =>
                //        {
                //            state1 = action(state1);
                //        });
                //    },
                //CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, taskFactory.Scheduler
                TaskHelpers.Delay(period, cancel.Token).ContinueWith(
                    t =>
                {
                    if (!t.IsCompletedSuccessfully)
                    {
                        return;
                    }

                    moveNext();

                    gate.Wait(() =>
                    {
                        state1 = action(state1);
                    });
                },
                    CancellationToken.None
                    );
            };

            moveNext();

            return(StableCompositeDisposable.Create(cancel, gate));
        }
示例#20
0
        /// <summary>
        /// CancellationDisposable 是 IDisposable 和 CancellationTokenSource 之间的适配器层
        /// 当调用 CancellationDisposable.Dispose() 时,CancellationTokenSource 会被 canceled
        /// </summary>
        public static void CancellationDisposable()
        {
            var cancelable = new CancellationDisposable();

            Task.Run(() =>
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));
                Console.WriteLine("Inner");
            }, cancelable.Token);
            cancelable.Dispose();
        }
        public void CancellationDisposable_Cancel_Test()
        {
            // arrange
            var cts  = new CancellationTokenSource();
            var disp = new CancellationDisposable(cts);

            // act & verify

            Assert.IsFalse(disp.IsDisposed);
            cts.Cancel();
            Assert.IsTrue(disp.IsDisposed);
        }
        public void CancellationDisposable_Dispose_Test()
        {
            // arrange
            var cts  = new CancellationTokenSource();
            var disp = new CancellationDisposable(cts);

            // act & verify

            Assert.IsFalse(cts.Token.IsCancellationRequested);
            disp.Dispose();
            Assert.IsTrue(cts.Token.IsCancellationRequested);
        }
示例#23
0
        public void DoesCleanupCall()
        {
            var cleanup  = new CancellationDisposable();
            var repoMock = Substitute.For <IGitRepository>();

            new RepositoryCheckout(
                new Lazy <IGitRepository>(repoMock),
                cleanup)
            .Dispose();
            cleanup.IsDisposed.Should().BeTrue();
            repoMock.Received().Dispose();
        }
示例#24
0
        private void DoFrameIdleCallback(object sender, FrameEventArgs e)
        {
            if (Volatile.Read(ref _suspended))
            {
                return;
            }

            var cancellationDisposable = new CancellationDisposable();

            _idleCancellationDisposable.Disposable = cancellationDisposable;
            Context.RunOnJavaScriptQueueThread(() => DoIdleCallback(e.FrameTime, cancellationDisposable.Token));
        }
        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 static IObservable <T> ToObservable <T>(this IAsyncEnumerable <T> asyncEnumerable)
        {
            return(Observable.Create <T>(async observer =>
            {
                var enumerator = await asyncEnumerable.GetAsyncEnumeratorAsync();
                var cancellationDisposable = new CancellationDisposable();

                ReadAndPublishAsync(enumerator, observer, cancellationDisposable.Token);


                return cancellationDisposable;
            }));
        }
示例#27
0
            public IDisposable Subscribe(IObserver <Unit> observer)
            {
                if (observer == null)
                {
                    throw new ArgumentNullException(nameof(observer));
                }

                var cts     = new CancellationDisposable();
                var options = GetTaskContinuationOptions(_scheduler);

                if (_scheduler == null)
                {
                    _task.ContinueWith(static (t, subjectObject) => t.EmitTaskResult((IObserver <Unit>)subjectObject !), observer, cts.Token, options, TaskScheduler.Current);
示例#28
0
        public virtual IObservable <TResult> Create <TResult>(Func <IObserver <TResult>, CancellationToken, Task> subscribeAsync)
        {
            return(new AnonymousObservable <TResult>(observer =>
            {
                var cancellable = new CancellationDisposable();

                var taskObservable = subscribeAsync(observer, cancellable.Token).ToObservable();
                var taskCompletionObserver = new AnonymousObserver <Unit>(Stubs <Unit> .Ignore, observer.OnError, observer.OnCompleted);
                var subscription = taskObservable.Subscribe(taskCompletionObserver);

                return StableCompositeDisposable.Create(cancellable, subscription);
            }));
        }
        public IDisposable LinkTo(ITargetBlock <TOutput> target, DataflowLinkOptions linkOptions)
        {
            IDisposable unlink = Source.LinkTo(target, linkOptions);

            OnLinkTo(Name, target, linkOptions);

            var trigerDisposable = new CancellationDisposable();

            trigerDisposable.Token.Register(() => OnUnlinkTo(Name, target));
            var dispComposite = new CompositeDisposable(trigerDisposable, unlink);

            return(dispComposite);
        }
示例#30
0
        private void OnSourceChanged(ImageSource oldValue, ImageSource newValue)
        {
            if (_image == null)
            {
                return;
            }

            _image.Source = newValue;

            if (newValue == null)
            {
                _loadingSubscription.Disposable = null;
                _image.Opacity       = 1;
                _waitingText.Opacity = 0;
                return;
            }

            _image.Opacity       = 0.5;
            _waitingText.Opacity = 1;

            _waitingText.Text = $"Waiting for source {GetTail((newValue as BitmapImage)?.UriSource.ToString() ?? "<null>")} to load.";

            var cd = new CancellationDisposable();

            _loadingSubscription.Disposable = cd;
            var ct = cd.Token;

            var t = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, SetImageVisible);

            async void SetImageVisible()
            {
                try
                {
                    const int delayms = 1000;
                    const int ticks   = 10;
                    for (int i = 0; i < ticks; i++)
                    {
                        await Task.Delay(delayms / ticks, ct);

                        _image.Opacity = (double)(i + 1) / (double)ticks;
                        if (ct.IsCancellationRequested)
                        {
                            return;
                        }
                    }
                    _image.Opacity       = 1;
                    _waitingText.Opacity = 0;
                }
                catch (Exception) { }
            }
        }