public void TestInvocationBehaviourIgnore() { OcDispatcher dispatcher = new OcDispatcher(); dispatcher.NewInvocationBehaviour = NewInvocationBehaviour.Cancel; bool called = false; dispatcher.Invoke(() => { called = true; }); dispatcher.Invoke(s => { called = true; }, new object()); dispatcher.InvokeAsync(() => { called = true; }); dispatcher.InvokeAsync(s => { called = true; }, new object()); dispatcher.Invoke(() => { called = true; return(0); }); dispatcher.Invoke(s => { called = true; return(0); }, new object()); dispatcher.InvokeAsync(() => { called = true; return(0); }); dispatcher.InvokeAsync(s => { called = true; return(0); }, new object()); dispatcher.InvokeAsyncAwaitable(() => { called = true; }); dispatcher.InvokeAsyncAwaitable(s => { called = true; }, new object()); dispatcher.InvokeAsyncAwaitable(() => { called = true; return(0); }); dispatcher.InvokeAsyncAwaitable(s => { called = true; return(0); }, new object()); dispatcher.NewInvocationBehaviour = NewInvocationBehaviour.Accept; dispatcher.Pass(); Assert.IsFalse(called); dispatcher.Dispose(); }
public MarketDataObservable(CurrencyPair currencyPair, OcDispatcher backgroundOcDispatcher) { var spread = currencyPair.DefaultSpread; var midRate = currencyPair.InitialPrice; var bid = midRate - (spread * currencyPair.PipSize); var offer = midRate + (spread * currencyPair.PipSize); var initial = new MarketData(currencyPair.Code, bid, offer); var currentPrice = initial; Value = currentPrice; var random = new Random(); //for a given period, move prices by up to 5 pips _recurringAction = new RecurringAction(() => { int pips = random.Next(1, 5); //move up or down between 1 and 5 pips var adjustment = Math.Round(pips * currencyPair.PipSize, currencyPair.DecimalPlaces); MarketData marketData = random.NextDouble() > 0.5 ? currentPrice + adjustment : currentPrice - adjustment; backgroundOcDispatcher.Invoke(() => Value = marketData); }, () => TimeSpan.FromSeconds(1 / (double)currencyPair.TickFrequency)); }
/// <summary>Raises the <see cref="E:System.Windows.Application.Startup" /> event.</summary> /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param> protected override void OnStartup(StartupEventArgs e) { _container = new Container(x => x.AddRegistry <AppRegistry>()); var factory = _container.GetInstance <WindowFactory>(); var window = factory.Create(true); _container.Configure(x => x.For <Dispatcher>().Add(window.Dispatcher)); _container.Configure(x => x.For <WpfOcDispatcher>().Add(new WpfOcDispatcher(window.Dispatcher))); _containerOcDispatcher = _container.GetNestedContainer(); OcDispatcher backgroundOcDispatcher = new OcDispatcher(2); _containerOcDispatcher.Configure(x => x.For <OcDispatcher>().Add(backgroundOcDispatcher)); _container.Configure(x => x.For <OcDispatcher>().Add(() => backgroundOcDispatcher)); _container.Configure(x => x.For <UserInputThrottlingOcDispatcher>().Add( new UserInputThrottlingOcDispatcher(backgroundOcDispatcher))); //configure dependency resolver for RxUI / Splat //var resolver = new ReactiveUIDependencyResolver(_container); //resolver.Register(() => new LogEntryView(), typeof(IViewFor<LogEntryViewer>)); //Locator.Current = resolver; //RxApp.SupportsRangeNotifications = false; //run start up jobs _container.GetInstance <TradePriceUpdateJob>(); _container.GetInstance <TradeAgeUpdateJob>(); window.Show(); base.OnStartup(e); }
private void LogChanges(OcDispatcher logPropertyChangedOcDispatcher) { const string messageTemplate = "{0} {1} {2} ({4}). Status = {3}"; void log(Trade trade) { _logger.Info( string.Format(messageTemplate, trade.BuyOrSell, trade.Amount, trade.CurrencyPair, trade.Status, trade.Customer)); } All .CollectionItemProcessing( (newTrade, processing) => { if (!processing.ActivationInProgress) { log(newTrade); } }) .For(_consumer); }
public void DoerTest() { OcConfiguration.SaveOcDispatcherInvocationExecutionStackTrace = true; OcDispatcher dispatcher = new OcDispatcher(); ManualResetEventSlim mre = new ManualResetEventSlim(false); dispatcher.InvokeAsync(() => { mre.Wait(); }); Invocation doer = dispatcher.InvokeAsync(() => { dispatcher.Pass(); }); Invocation invocation = dispatcher.InvokeAsync(() => {}); mre.Set(); dispatcher.Pass(); Assert.AreEqual(invocation.Executor, doer); Assert.IsNotNull(invocation.ExecutionStackTrace); dispatcher.Dispose(); }
public void DisposeTest() { OcDispatcher dispatcher = new OcDispatcher(); ManualResetEventSlim mre = new ManualResetEventSlim(false); bool invoked1 = false; bool invoked2 = false; bool freezed = false; InvocationResult <bool> invocationResult = null; InvocationResult <bool> invocationResult1 = null; dispatcher.InvokeAsync(() => { dispatcher.InvokeAsync(() => { freezed = true; mre.Wait(); }); invocationResult = dispatcher.Invoke(() => invoked1 = true); }); Thread thread = new Thread( () => { while (!freezed) { } invocationResult1 = dispatcher.Invoke(() => invoked2 = true); }); thread.Start(); ManualResetEventSlim mreDisposed = new ManualResetEventSlim(false); dispatcher.PropertyChanged += (sender, args) => { if (args.PropertyName == nameof(OcDispatcher.Status) && dispatcher.Status == OcDispatcherStatus.Disposed) { mreDisposed.Set(); } }; while (dispatcher.GetQueueCount() != 2) { } dispatcher.Dispose(); mre.Set(); thread.Join(); mreDisposed.Wait(); Assert.IsFalse(invoked1); Assert.IsFalse(invoked2); Assert.AreEqual(invocationResult.Invocation.Status, InvocationStatus.Canceled); Assert.AreEqual(invocationResult1.Invocation.Status, InvocationStatus.Canceled); }
public void TestFuncSyncState() { OcDispatcher dispatcher = new OcDispatcher(2); object returnObject = new object(); Assert.AreEqual(dispatcher.Invoke(s => returnObject, new object()).Value, returnObject); dispatcher.Dispose(); }
public NearToMarketViewer(INearToMarketService nearToMarketService, OcDispatcher backgroundOcDispatcher, WpfOcDispatcher wpfOcDispatcher) { Data = nearToMarketService.Query(() => (decimal)NearToMarketPercent) .Ordering(t => t.Timestamp, ListSortDirection.Descending) .Selecting(t => new TradeProxy(t)) .CollectionDisposing() .CollectionDispatching(wpfOcDispatcher, backgroundOcDispatcher, 0, 1) .For(_consumer); }
public TradesByTimeViewer(ITradeService tradeService, OcDispatcher backgroundOcDispatcher, WpfOcDispatcher wpfOcDispatcher) { Data = tradeService.All .Grouping(trade => trade.Age) .Selecting(group => new TradesByTime(group, _consumer, backgroundOcDispatcher, wpfOcDispatcher)) .Ordering(t => t.Period) .CollectionDispatching(wpfOcDispatcher, backgroundOcDispatcher, 0, 1) .For(_consumer); }
public MarketDataService(IStaticData staticData, OcDispatcher backgroundOcDispatcher) { _backgroundOcDispatcher = backgroundOcDispatcher; foreach (var item in staticData.CurrencyPairs) { _marketDataObservables[item.Code] = CreateObservableMarketData(item); } }
public PositionsViewer(ITradeService tradeService, OcDispatcher backgroundOcDispatcher, WpfOcDispatcher wpfOcDispatcher) { Data = tradeService.Live .Grouping(trade => trade.CurrencyPair) .Selecting(group => new CurrencyPairPosition(group, _consumer)) .Ordering(p => p.CurrencyPair) .CollectionDispatching(wpfOcDispatcher, backgroundOcDispatcher, 0, 1) .For(_consumer); }
public TradesByPercentViewer(INearToMarketService nearToMarketService, OcDispatcher backgroundOcDispatcher, WpfOcDispatcher wpfOcDispatcher) { Data = nearToMarketService.Query(() => 4) .Grouping(trade => (int)Math.Truncate(Math.Abs(trade.PercentFromMarket.Value))) .Selecting(group => new Domain.Model.TradesByPercentDiff(group, _consumer, backgroundOcDispatcher, wpfOcDispatcher)) .Ordering(tbpd => tbpd.PercentBand) .CollectionDispatching(wpfOcDispatcher, backgroundOcDispatcher, 0, 1) .For(_consumer); }
public void TestFuncAsync() { OcDispatcher dispatcher = new OcDispatcher(2); object returnObject = new object(); InvocationResult <object> invocationResult = dispatcher.InvokeAsync(() => returnObject); dispatcher.Pass(); Assert.AreEqual(invocationResult.Value, invocationResult.Value); Assert.AreEqual(invocationResult.ToString(), "(ObservableComputations.InvocationResult<Object> (Value = '(System.Object)'))"); dispatcher.Dispose(); }
public void DisableThreadComObjectEagerCleanupTest() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return; } OcDispatcher dispatcher = new OcDispatcher(); dispatcher.DisableThreadComObjectEagerCleanup(); dispatcher.Dispose(); }
public TradesByTime([NotNull] Group <Trade, TimePeriod> group, OcConsumer consumer, OcDispatcher backgroundOcDispatcher, WpfOcDispatcher wpfOcDispatcher) { Period = group?.Key ?? throw new ArgumentNullException(nameof(group)); Data = group .Ordering(t => t.Timestamp, ListSortDirection.Descending) .Selecting(trade => new TradeProxy(trade)) .CollectionDisposing() .CollectionDispatching(wpfOcDispatcher, backgroundOcDispatcher, 0, 1) .For(consumer); }
public RecentTradesViewer(ITradeService tradeService, OcDispatcher backgroundOcDispatcher, WpfOcDispatcher wpfOcDispatcher) { DateTime initialDateTime = DateTime.Now; Data = tradeService.All .Filtering(t => !t.Expired && t.Timestamp > initialDateTime) .Ordering(t => t.Timestamp, ListSortDirection.Descending) .Selecting(t => new TradeProxy(t)) .CollectionDisposing() .CollectionDispatching(wpfOcDispatcher, backgroundOcDispatcher, 0, 1) .For(_consumer); }
internal Invocation(Action action, int priority, OcDispatcher ocDispatcher, bool setSynchronizationContext, Invocation parent, string instantiationStackTrace, object context = null, ManualResetEventSlim doneManualResetEvent = null) { _action = action; _priority = priority; _ocDispatcher = ocDispatcher; _setSynchronizationContext = setSynchronizationContext; _context = context; _doneManualResetEvent = doneManualResetEvent; _instantiationStackTrace = instantiationStackTrace; _parent = parent; }
internal Invocation(Action action, OcDispatcher ocDispatcher, InvocationStatus invocationStatus, object context = null, ManualResetEventSlim doneManualResetEvent = null) : this() { _action = action; _ocDispatcher = ocDispatcher; _context = context; InvocationStatus = invocationStatus; _doneManualResetEvent = doneManualResetEvent; if (Configuration.SaveOcDispatcherInvocationStackTrace) { _callStackTrace = Environment.StackTrace; } }
public LiveTradesViewer(ITradeService tradeService, SearchHints searchHints, OcDispatcher backgroundOcDispatcher, WpfOcDispatcher wpfOcDispatcher) { SearchHints = searchHints; Data = tradeService.Live .CollectionPausing(new Computing <bool>(() => Paused).ScalarDispatching(backgroundOcDispatcher, wpfOcDispatcher)) .Filtering(t => t.CurrencyPair.Contains(SearchHints.SearchTextThrottled.Value, StringComparison.OrdinalIgnoreCase) || t.Customer.Contains(SearchHints.SearchTextThrottled.Value, StringComparison.OrdinalIgnoreCase)) .Ordering(t => t.Timestamp, ListSortDirection.Descending) .Selecting(t => new TradeProxy(t)) .CollectionDisposing() .CollectionDispatching(wpfOcDispatcher, backgroundOcDispatcher, 0, 1) .For(_consumer); }
public void TestFuncAsyncState() { OcDispatcher dispatcher = new OcDispatcher(2); TestValue returnObject = new TestValue(); InvocationResult <TestValue> invocationResult = dispatcher.InvokeAsync(s => returnObject, new object()); bool propertyChanged = false; invocationResult.PropertyChanged += (sender, args) => propertyChanged = true; dispatcher.Pass(); Assert.AreEqual(invocationResult.Value, returnObject); Assert.IsTrue(propertyChanged); Assert.AreEqual(invocationResult.ToString(), "(ObservableComputations.InvocationResult<TestValue> (Value = 'Mesasage'))"); Assert.AreEqual(invocationResult.Invocation.Status, InvocationStatus.Executed); dispatcher.Dispose(); }
internal Invocation(Action <object> actionWithState, object state, OcDispatcher ocDispatcher, InvocationStatus invocationStatus, IComputing context = null, ManualResetEventSlim doneManualResetEvent = null) : this() { _actionWithState = actionWithState; _state = state; _ocDispatcher = ocDispatcher; _context = context; InvocationStatus = invocationStatus; _doneManualResetEvent = doneManualResetEvent; if (Configuration.SaveOcDispatcherInvocationStackTrace) { _callStackTrace = Environment.StackTrace; } }
public TradePriceUpdateJob(ITradeService tradeService, IMarketDataService marketDataService, Dispatcher dispatcher, OcDispatcher backgroundOcDispatcher) { _backgroundOcDispatcher = backgroundOcDispatcher; tradeService.All .Grouping(t => t.CurrencyPair) .CollectionItemProcessing( (newTradeGroup, _) => { IReadScalar <MarketData> observableMarketData = marketDataService.Get(newTradeGroup.Key); OcConsumer consumer1 = new OcConsumer(); //DataHasChanged newTradeGroup.CollectionItemsProcessing( (newTrades, __) => { Trade[] newTradesCopy = newTrades.ToArray(); dispatcher.Invoke(() => { foreach (Trade trade in newTradesCopy) { trade.MarketPrice = observableMarketData.Value.Bid; } }, DispatcherPriority.Background); }) .For(consumer1); observableMarketData.Binding((newMarketData, __) => { decimal bid = observableMarketData.Value.Bid; Trade[] tradesGroupCopy = newTradeGroup.ToArray(); dispatcher.Invoke(() => { tradesGroupCopy.ForEach(trade => trade.MarketPrice = bid); }, DispatcherPriority.Background); }).For(consumer1); return(consumer1); }) .CollectionDisposing() .For(_consumer); }
public Item(int num, int num2, OcDispatcher mainOcDispatcher, OcDispatcher backgroundOcDispatcher) { _num = num; _num2 = num2; _numBackgroundToMainDispatching = new PropertyDispatching <Item, int>(this, nameof(Num), mainOcDispatcher, backgroundOcDispatcher).For(Consumer); _num2MainToBackgroundDispatching = new PropertyDispatching <Item, int>(this, nameof(Num2), backgroundOcDispatcher, mainOcDispatcher).For(Consumer); _numBackgroundToMainScalarDispatching = new Computing <int>(() => Num).ScalarDispatching(mainOcDispatcher, backgroundOcDispatcher).For(Consumer); _num2MainToBackgroundScalarDispatching = new Computing <int>(() => Num2).ScalarDispatching(backgroundOcDispatcher, mainOcDispatcher).For(Consumer); _numBackgroundToMainScalarDispatching.SetValueRequestHandler = i => { backgroundOcDispatcher.Invoke(() => Num = i); }; _num2MainToBackgroundDispatching.PropertyChanged += (sender, args) => { if (Thread.CurrentThread != backgroundOcDispatcher._thread) { throw new Exception("Wrong thread"); } }; _num2MainToBackgroundScalarDispatching.PropertyChanged += (sender, args) => { if (Thread.CurrentThread != backgroundOcDispatcher._thread) { throw new Exception("Wrong thread"); } }; _numBackgroundToMainDispatching.PropertyChanged += (sender, args) => { if (Thread.CurrentThread != mainOcDispatcher._thread) { throw new Exception("Wrong thread"); } }; _numBackgroundToMainScalarDispatching.PropertyChanged += (sender, args) => { if (Thread.CurrentThread != mainOcDispatcher._thread) { throw new Exception("Wrong thread"); } }; }
public void TestCallAwaitable() { TestSynchronizationConext testSynchronizationConext = new TestSynchronizationConext(); SynchronizationContext.SetSynchronizationContext(testSynchronizationConext); OcDispatcher dispatcher = new OcDispatcher(2); int count = 1; ManualResetEventSlim mres = new ManualResetEventSlim(false); object context = new object(); Invocation parent; dispatcher.InvokeAsync(() => { parent = dispatcher.CurrentInvocation; dispatcher.Invoke(async() => { Assert.AreEqual(count, 1); count++; Assert.AreEqual(dispatcher.CurrentInvocation.Priority, 1); Assert.AreEqual(dispatcher.CurrentInvocation.Context, context); Assert.AreEqual(dispatcher.CurrentInvocation.Parent, parent); OcDispatcherSynchronizationContext synchronizationContext = (OcDispatcherSynchronizationContext)SynchronizationContext.Current; Assert.AreEqual(synchronizationContext.Priority, 1); Assert.AreEqual(synchronizationContext.Context, context); Assert.AreEqual(synchronizationContext.ParentInvocation, parent); await Task.Run(() => count++); Assert.AreEqual(dispatcher.CurrentInvocation.Priority, 1); Assert.AreEqual(dispatcher.CurrentInvocation.Context, context); Assert.AreEqual(dispatcher.CurrentInvocation.Parent, parent); count++; mres.Set(); return(1); }, 1, context, true); }); mres.Wait(); mres.Dispose(); Assert.AreEqual(count, 4); dispatcher.Dispose(); }
private void App_OnExit(object sender, ExitEventArgs e) { OcDispatcher backgroundOcDispatcher = _container.GetInstance <OcDispatcher>(); _container.Dispose(); while (!RecurringAction.AllInstancesIsDisposed) { Dispatcher.Invoke(() => { }, DispatcherPriority.Background); } while (backgroundOcDispatcher.GetQueueCount() > 0) { Thread.Sleep(10); } _containerOcDispatcher.Dispose(); }
public void TestInvokeAsyncAwaitableFuncStateDispatcherThread() { OcDispatcher dispatcher = new OcDispatcher(2); int count = 0; ManualResetEventSlim mres = new ManualResetEventSlim(false); object context = new object(); dispatcher.Invoke(() => { Invocation invocation = dispatcher.CurrentInvocation; dispatcher.InvokeAsync(async() => { count++; Assert.AreEqual(dispatcher.CurrentInvocation.Parent, invocation); Assert.IsTrue(dispatcher.CurrentInvocation.SetSynchronizationContext); int returnCount = await dispatcher.InvokeAsyncAwaitable(state => { Assert.AreEqual(count, 1); count++; Assert.AreEqual(dispatcher.CurrentInvocation.Priority, 0); Assert.AreEqual(dispatcher.CurrentInvocation.Context, null); return(count); }, new object()); Assert.AreEqual(dispatcher.CurrentInvocation.Parent, invocation); Assert.AreEqual(returnCount, 2); Assert.AreEqual(count, 2); count++; Assert.AreEqual(Thread.CurrentThread.ManagedThreadId, dispatcher.ManagedThreadId); Assert.AreEqual(dispatcher.CurrentInvocation.Priority, 1); Assert.AreEqual(dispatcher.CurrentInvocation.Context, context); mres.Set(); }, 1, context, true); }); mres.Wait(); mres.Dispose(); Assert.AreEqual(count, 3); dispatcher.Dispose(); }
public void TestInvocationBehaviourThrowException() { OcDispatcher dispatcher = new OcDispatcher(); dispatcher.NewInvocationBehaviour = NewInvocationBehaviour.ThrowException; bool called = false; Exception exception; void invoke(Action action) { exception = null; try { action(); } catch (Exception e) { exception = e; } Assert.IsTrue(exception != null); } invoke(() => dispatcher.Invoke(() => { called = true; })); invoke(() => dispatcher.Invoke(s => { called = true; }, new object())); invoke(() => dispatcher.InvokeAsync(() => { called = true; })); invoke(() => dispatcher.InvokeAsync(s => { called = true; }, new object())); invoke(() => dispatcher.Invoke(() => { called = true; return(0); })); invoke(() => dispatcher.Invoke(s => { called = true; return(0); }, new object())); invoke(() => dispatcher.InvokeAsync(() => { called = true; return(0); })); invoke(() => dispatcher.InvokeAsync(s => { called = true; return(0); }, new object())); dispatcher.NewInvocationBehaviour = NewInvocationBehaviour.Accept; dispatcher.Pass(); Assert.IsFalse(called); dispatcher.Dispose(); }
public void TestInvokeAsyncAwaitableFuncStateNonDispatcherThread() { TestSynchronizationConext testSynchronizationConext = new TestSynchronizationConext(); SynchronizationContext.SetSynchronizationContext(testSynchronizationConext); OcDispatcher dispatcher = new OcDispatcher(2); int count = 0; ManualResetEventSlim mres = new ManualResetEventSlim(false); object context = new object(); async void test() { count++; int count1 = await dispatcher.InvokeAsyncAwaitable(state => { Assert.AreEqual(count, 1); count++; Assert.AreEqual(dispatcher.CurrentInvocation.Priority, 1); Assert.AreEqual(dispatcher.CurrentInvocation.Context, context); return(count); }, new object(), 1, context); Assert.AreEqual(count1, 2); Assert.AreEqual(count, 2); count++; Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, dispatcher.ManagedThreadId); Assert.AreEqual(dispatcher.CurrentInvocation, null); mres.Set(); } test(); mres.Wait(); mres.Dispose(); Assert.AreEqual(count, 3); dispatcher.Dispose(); }
public PagedDataViewer(ITradeService tradeService, SearchHints searchHints, OcDispatcher backgroundOcDispatcher, WpfOcDispatcher wpfOcDispatcher) { SearchHints = searchHints; SortParameters = new SortParameterData( tradeService.Live .Selecting(t => new TradeProxy(t)) .CollectionDisposing(), _consumer); AllData = new Computing <ObservableCollection <TradeProxy> >( () => SortParameters.SelectedItem.SortedData) .Filtering(t => t.Trade.CurrencyPair.Contains(SearchHints.SearchTextThrottled.Value, StringComparison.OrdinalIgnoreCase) || t.Trade.Customer.Contains(SearchHints.SearchTextThrottled.Value, StringComparison.OrdinalIgnoreCase)) .CollectionDispatching(wpfOcDispatcher, backgroundOcDispatcher, 0, 1); Data = AllData.Paging(25, 1).For(_consumer); _nextPageCommand = new Command(() => Data.CurrentPage = Data.CurrentPage + 1, () => Data.CurrentPage < Data.PageCount); _previousPageCommand = new Command(() => Data.CurrentPage = Data.CurrentPage - 1, () => Data.CurrentPage > 1); }
public TradeAgeUpdateJob(OcDispatcher backgroundOcDispatcher, ITradeService tradeService) { _recurringAction = new RecurringAction(() => { Trade[] trades = null; backgroundOcDispatcher.Invoke(() => trades = tradeService.All.ToArray()); if (trades != null) { foreach (IEnumerable <Trade> tradesSlice in trades.Split(300)) { backgroundOcDispatcher.Invoke(() => { foreach (Trade trade in tradesSlice) { TimeSpan diff = DateTime.Now.Subtract(trade.Timestamp); TimePeriod age = diff.TotalSeconds <= 60 ? TimePeriod.LastMinute : diff.TotalMinutes <= 60 ? TimePeriod.LastHour : TimePeriod.Older; trade.Age = age; if (diff.TotalSeconds > 30) { trade.Expired = true; } } }); } } }, () => TimeSpan.FromSeconds(1)); }