protected ConcurrentObservableBase(bool isMultithreaded, TInternalCollection initialCollection)
        {
            // If compiled as debug, then store the stack trace as an aid to working out which object this is in case of a binding error.
            // This is non performant, so only use this in debug builds.
#if DEBUG
            // This function checks if the declaring class of a method in a stack frame inherits from the base type name passed in.
            // Was unable to use Type.IsSubClassOf() due to the type being derived by reflection.
            bool InheritsFrom(StackFrame stackFrame, string baseNameTest)
            {
                var testType = stackFrame.GetMethod().DeclaringType;

                while (testType != null)
                {
                    if (testType.Name == baseNameTest)
                    {
                        return(true);
                    }
                    testType = testType.BaseType;
                }
                return(false);
            }

            // Get all the stack frames up to the point where this object was created. Omit the constructors for this object.
            StackTrace stackTrace = new StackTrace(true);
            var        baseName   = typeof(ConcurrentObservableBase <T, TInternalCollection>).Name;;
            _stackFrames = stackTrace.GetFrames().SkipWhile(frame => InheritsFrom(frame, baseName)).ToArray();
#endif
            _lock = isMultithreaded ? new ReaderWriterLockSlim() : null;
            _internalCollection = initialCollection;
            _viewChanged        = new ThrottledAction(() => OnPropertyChanged(nameof(CollectionView), nameof(Count)), TimeSpan.FromMilliseconds(20));
        }
        public ListBoxDragDropHelper(ListBox listBox, Action <int, IEnumerable <TItem> > moveItemsAction,
                                     Func <DragEventArgs, IEnumerable> tryGetInsertItemsAction, Action <int, IEnumerable> insertItemsAction)
        {
            this.listBox                 = listBox;
            this.moveItemsAction         = moveItemsAction;
            this.tryGetInsertItemsAction = tryGetInsertItemsAction ?? (eventArgs => null);
            this.insertItemsAction       = insertItemsAction;
            insertMarkerAdorner          = new InsertMarkerAdorner(listBox);
            throttledAutoScrollAction    = new ThrottledAction(ThrottledAutoScroll, ThrottledActionMode.InvokeMaxEveryDelayTime,
                                                               TimeSpan.FromMilliseconds(250));

            listBox.Loaded += ListBoxLoaded;
            if (listBox.IsLoaded)
            {
                InitializeAdornerLayer();
            }

            listBox.PreviewDragOver += ListBoxPreviewDragOver;
            listBox.Drop            += ListBoxDrop;

            var listboxItemStyle = new Style(typeof(ListBoxItem), listBox.ItemContainerStyle);

            listboxItemStyle.Setters.Add(new EventSetter(UIElement.PreviewMouseLeftButtonDownEvent,
                                                         (MouseButtonEventHandler)ListBoxItemPreviewMouseLeftButtonDown));
            listboxItemStyle.Setters.Add(new EventSetter(UIElement.PreviewMouseMoveEvent,
                                                         (MouseEventHandler)ListBoxItemPreviewMouseMove));
            listboxItemStyle.Setters.Add(new EventSetter(UIElement.DragEnterEvent, (DragEventHandler)ListBoxItemDragEnter));
            listboxItemStyle.Setters.Add(new EventSetter(UIElement.DragLeaveEvent, (DragEventHandler)ListBoxItemDragLeave));
            listboxItemStyle.Setters.Add(new EventSetter(UIElement.DropEvent, (DragEventHandler)ListBoxItemDrop));
            listBox.ItemContainerStyle = listboxItemStyle;
        }
        public void ConstructorTest()
        {
            AssertHelper.ExpectedException <ArgumentNullException>(() => new ThrottledAction(null));
            var throttledAction = new ThrottledAction(() => { });

            Assert.IsFalse(throttledAction.IsRunning);
        }
        public void InvokeOnlyIfIdleForDelayTimeWithoutSynchronizationContext()
        {
            Assert.IsNull(SynchronizationContext.Current);

            int actionCallCount = 0;
            var throttledAction = new ThrottledAction(() => Interlocked.Add(ref actionCallCount, 1), ThrottledActionMode.InvokeOnlyIfIdleForDelayTime, TimeSpan.FromMilliseconds(100));

            Assert.IsFalse(throttledAction.IsRunning);

            throttledAction.InvokeAccumulated();
            Assert.IsTrue(throttledAction.IsRunning);
            throttledAction.InvokeAccumulated();
            throttledAction.InvokeAccumulated();

            // Multiple calls of InvokeAccumulated within the delayTime should call the action just once.
            Task.Delay(200).Wait();
            Assert.AreEqual(1, actionCallCount);
            Assert.IsFalse(throttledAction.IsRunning);

            actionCallCount = 0;
            throttledAction.InvokeAccumulated();
            Task.Delay(60).Wait();
            throttledAction.InvokeAccumulated();
            Task.Delay(60).Wait();
            throttledAction.InvokeAccumulated();
            Task.Delay(60).Wait();
            throttledAction.InvokeAccumulated();

            // Calls just once: The waits between InvokeAccumulated are less than the idle (delay) time.
            Task.Delay(200).Wait();
            Assert.AreEqual(1, actionCallCount);
            Assert.IsFalse(throttledAction.IsRunning);
        }
Beispiel #5
0
 private void Awake()
 {
     serverState = new State();
     clientState = new State();
     networkedComponentTypeInfo = NetLib.GetNetworkedComponentTypeInfo(typeof(State));
     sendUpdateAction           = new ThrottledAction(SendUpdate, 0.25f);
 }
Beispiel #6
0
        public void InvokeOnlyIfIdleForDelayTimePerformanceTest()
        {
            int actionCallCount = 0;
            var throttledAction = new ThrottledAction(() => Interlocked.Add(ref actionCallCount, 1), ThrottledActionMode.InvokeOnlyIfIdleForDelayTime, TimeSpan.FromMilliseconds(10));

            for (int i = 0; i < 200000; i++)
            {
                throttledAction.InvokeAccumulated();
            }
            Task.Delay(100).Wait();
            Assert.AreEqual(1, actionCallCount);
        }
Beispiel #7
0
    public void Start()
    {
        ClientPeer = new ClientPeer();
        ClientPeer.OnConnectedToServer      += InternalOnConnectedToServer;
        ClientPeer.OnDisconnectedFromServer += InternalOnDisconnectedFromServer;
        ClientPeer.ShouldApplyStateSnapshots = false;

        ClientPeer.Start(this, CreateGameObjectFromState);

        SendInputPeriodicFunction = new ThrottledAction(SendPlayerInput, SendPlayerInputInterval);

        Camera = Object.Instantiate(OsFps.Instance.CameraPrefab);

        CreateGui();
    }
Beispiel #8
0
 public WorkspaceController(IDocumentService documentService, Lazy <ShellViewModel> shellViewModel, Lazy <ErrorListViewModel> errorListViewModel,
                            Lazy <OutputViewModel> outputViewModel, ScriptHost host)
 {
     taskScheduler           = TaskScheduler.FromCurrentSynchronizationContext();
     this.documentService    = documentService;
     this.shellViewModel     = shellViewModel;
     this.errorListViewModel = errorListViewModel;
     this.outputViewModel    = outputViewModel;
     this.host = host;
     this.updateDiagnosticsAction = new ThrottledAction(UpdateDiagnostics, ThrottledActionMode.InvokeOnlyIfIdleForDelayTime, TimeSpan.FromSeconds(2));
     this.outputTextWriter        = new DelegateTextWriter(AppendOutputText);
     this.errorTextWriter         = new DelegateTextWriter(AppendErrorText);
     this.startCommand            = new DelegateCommand(StartScript, CanStartScript);
     this.stopCommand             = new DelegateCommand(StopScript, CanStopScript);
     this.documentIds             = new Dictionary <DocumentFile, DocumentId>();
 }
Beispiel #9
0
        public void InvokeMaxEveryDelayTimeTestWithoutSynchronizationContext()
        {
            Assert.IsNull(SynchronizationContext.Current);

            int actionCallCount = 0;
            var throttledAction = new ThrottledAction(() => Interlocked.Add(ref actionCallCount, 1), ThrottledActionMode.InvokeMaxEveryDelayTime, TimeSpan.FromMilliseconds(100));

            Assert.IsFalse(throttledAction.IsRunning);

            throttledAction.InvokeAccumulated();
            Assert.IsTrue(throttledAction.IsRunning);
            throttledAction.InvokeAccumulated();
            throttledAction.InvokeAccumulated();

            // Multiple calls of InvokeAccumulated within the delayTime should call the action just once.
            Task.Delay(200).Wait();
            Assert.AreEqual(1, actionCallCount);
            Assert.IsFalse(throttledAction.IsRunning);


            actionCallCount = 0;
            throttledAction.InvokeAccumulated();
            Task.Delay(10).Wait();
            throttledAction.InvokeAccumulated();
            Task.Delay(150).Wait();
            throttledAction.InvokeAccumulated();

            // Calls the action twice: First 2 InvokeAccumulated are within delayTime; Last is after delayTime.
            Task.Delay(200).Wait();
            Assert.AreEqual(2, actionCallCount);
            Assert.IsFalse(throttledAction.IsRunning);


            actionCallCount = 0;
            throttledAction.InvokeAccumulated();
            Task.Delay(10).Wait();
            throttledAction.Cancel();

            // Do not call the action because it is cancelled.
            Task.Delay(200).Wait();
            Assert.AreEqual(0, actionCallCount);
            Assert.IsFalse(throttledAction.IsRunning);

            // Calling Cancel multiple time most not throw an exception
            throttledAction.Cancel();
            throttledAction.Cancel();
        }
 public TranscodingController(IMessageService messageService, IShellService shellService, IMusicFileContext musicFileContext, ISelectionService selectionService,
                              TranscodingService transcodingService, Lazy <ITranscoder> transcoder, Lazy <TranscodingListViewModel> transcodingListViewModel)
 {
     this.messageService           = messageService;
     this.shellService             = shellService;
     this.musicFileContext         = musicFileContext;
     this.selectionService         = selectionService;
     this.transcodingService       = transcodingService;
     this.transcoder               = transcoder;
     this.transcodingListViewModel = transcodingListViewModel;
     cancellationTokenSources      = new Dictionary <TranscodeItem, CancellationTokenSource>();
     convertToMp3AllCommand        = new DelegateCommand(ConvertToMp3All, CanConvertToMp3All);
     convertToMp3SelectedCommand   = new DelegateCommand(ConvertToMp3Selected, CanConvertToMp3Selected);
     cancelAllCommand              = new DelegateCommand(CancelAll, CanCancelAll);
     cancelSelectedCommand         = new DelegateCommand(CancelSelected, CanCancelSelected);
     throttler          = new SemaphoreSlim(Environment.ProcessorCount); // Do not dispose the throttler; it is used after Shutdown to cancel the open tasks
     transcodingManager = new TranscodingManager();
     throttledMusicFilesCollectionChangedAction = new ThrottledAction(ThrottledMusicFilesCollectionChanged, ThrottledActionMode.InvokeOnlyIfIdleForDelayTime, TimeSpan.FromMilliseconds(10));
 }
Beispiel #11
0
        public void Start(
            ushort?portNumber, int maxPlayerCount, object objectContainingRpcs, float sendGameStateInterval
            )
        {
            ObjectContainingRpcs          = objectContainingRpcs;
            ShouldSendStateSnapshots      = true;
            sendGameStatePeriodicFunction = new ThrottledAction(SendGameState, sendGameStateInterval);
            this.maxPlayerCount           = maxPlayerCount;

            var connectionConfig = NetLib.CreateConnectionConfig(
                out reliableSequencedChannelId,
                out reliableChannelId,
                out unreliableStateUpdateChannelId,
                out unreliableFragmentedChannelId,
                out unreliableChannelId
                );
            var hostTopology = new HostTopology(connectionConfig, maxPlayerCount);

            Start(portNumber, hostTopology);
        }
Beispiel #12
0
        public void InvokeMaxEveryDelayTimeTestWithSynchronizationContext()
        {
            using var context = UnitTestSynchronizationContext.Create();
            int actionCallCount = 0;
            var throttledAction = new ThrottledAction(() => Interlocked.Add(ref actionCallCount, 1), ThrottledActionMode.InvokeMaxEveryDelayTime, TimeSpan.FromMilliseconds(100));

            Assert.IsFalse(throttledAction.IsRunning);

            throttledAction.InvokeAccumulated();
            Assert.IsTrue(throttledAction.IsRunning);
            throttledAction.InvokeAccumulated();
            throttledAction.InvokeAccumulated();

            // As long the unit test synchronization context is not executed the actionCallCount must not be increased.
            Task.Delay(200).Wait();
            Assert.AreEqual(0, actionCallCount);

            // Execute the unit test synchronization context.
            context.WaitFor(() => actionCallCount > 0, TimeSpan.FromMilliseconds(200));
            Assert.AreEqual(1, actionCallCount);
            Assert.IsFalse(throttledAction.IsRunning);
        }
        public PlayerView(PlayerService playerService)
        {
            this.InitializeComponent();
            this.viewModel        = new Lazy <PlayerViewModel>(() => ViewHelper.GetViewModel <PlayerViewModel>(this));
            this.playerService    = playerService;
            this.mediaPlayer      = new MediaPlayer();
            this.duratonConverter = new Converters.DurationConverter();

            updateTimer          = new DispatcherTimer();
            updateTimer.Interval = TimeSpan.FromMilliseconds(100);
            updateTimer.Tick    += UpdateTimerTick;

            throttledSliderValueChangedAction = new ThrottledAction(ThrottledSliderValueChanged, ThrottledActionMode.InvokeMaxEveryDelayTime, TimeSpan.FromMilliseconds(100));

            previousCommand  = new DelegateCommand(Previous, CanPrevious);
            playPauseCommand = new DelegateCommand(PlayPause, CanPlayPause);
            nextCommand      = new DelegateCommand(Next, CanNext);
            playerService.PreviousCommand  = previousCommand;
            playerService.PlayPauseCommand = playPauseCommand;
            playerService.NextCommand      = nextCommand;
            playerService.IsPlayCommand    = true;

            Loaded += FirstTimeLoadedHandler;
        }
Beispiel #14
0
 public FeedViewModel(IFeedView view) : base(view, false)
 {
     updateSearchAction = new ThrottledAction(UpdateSearch);
     UpdateItemsListView();
 }
Beispiel #15
0
 protected ConcurrentObservableBase(bool isMultithreaded, TInternalCollection initialCollection)
 {
     _lock = isMultithreaded ? new ReaderWriterLockSlim() : null;
     _internalCollection = initialCollection;
     _viewChanged        = new ThrottledAction(() => OnPropertyChanged(nameof(CollectionView), nameof(Count)), TimeSpan.FromMilliseconds(20));
 }