public async Task Test3() { SetupNlog.Initialize("bla"); MappingExtensions.Mapper = new MapperConfiguration(cfg => { cfg.AddProfile<ArmaServerProfile>(); }).CreateMapper(); var f = new SteamSession.SteamSessionFactory(); var id = (uint)SteamGameIds.Arma2Oa; LockedWrapper.callFactory = new SafeCallFactory(); // workaround for accessviolation errors var c = await f.Do(id, SteamHelper.Create().SteamPath, async () => { using (var scheduler = new EventLoopScheduler()) { using (var obs2 = new Subject<ArmaServerInfoModel>()) { var s = obs2.Synchronize() .ObserveOn(scheduler) .Buffer(24) //.Do(x => Console.WriteLine("r" + x.ToList<ServerInfoModel>())) .SelectMany(x => x) .Count() .ToTask(); var c2 = await SteamServers.GetServers(f, true, ServerFilterBuilder.Build().FilterByAppId(id).FilterByDedicated().Value, obs2.OnNext) .ConfigureAwait(false); obs2.OnCompleted(); return new BatchResult(await s); } } }).ConfigureAwait(false); }
void Test(bool hasDelay) { var mockStatusUPdates = new Notification[] { new Notification(StatusSeverity.Fail, "fail"), new Notification(StatusSeverity.Info, "info"), new Notification(StatusSeverity.Warn, "warn"), new Notification(StatusSeverity.Success, "really long text with a lot of text alsdjfksjadfl;jkasdflkjs;dfjslkjfdskljdfklsj;dfljslkdfjskldfjlsjdfkljsdfjslkdjfkl"), }; var statusFeedDelay = Observable.Create<Notification>(o => { var els = new EventLoopScheduler(); return mockStatusUPdates.ToObservable()//repoObjectsTree.StatusFeed .ObserveOn(els) .Do(x => els.Schedule(() => Thread.Sleep(5 * 1000))) .Subscribe(o); }); var observable = hasDelay ? statusFeedDelay// this one adds them all at once : mockStatusUPdates.ToObservable();// this on //observable // .ObserveOn(this) // .DelaySubscription(TimeSpan.FromSeconds(2)) // .Subscribe(notifier.Notify); }
public JobProcessor(IProcessorObserver processorObserver, IJobObserver jobObserver) { this.processorObserver = processorObserver; this.jobObserver = jobObserver; jobScheduler = new EventLoopScheduler(); CurrentState = new Created(); }
public ObservableComponent(DataFlowComponent comp) { _component = comp; var observer = new ComponentObserverImpl(); var conf = _component.GetConfiguration(); _profile = new ServiceProfile(); _profile.Id = Guid.NewGuid().ToString(); _profile.InterfaceType = "IDL:OpenRTM/ComponentObserver:1.0"; _profile.Properties = new Dictionary<string, object>(); _profile.Properties["observed_status"] = "ALL"; _profile.Properties["heartbeat.enable"] = "YES"; _profile.Properties["heartbeat.interval"] = "1"; _profile.Service = observer; if (conf.AddServiceProfile(_profile)) { observer.Subscribe(Notify); } ExecutionContextScheduler = new EventLoopScheduler(); }
public static void NoSemaphoreFullException() { var failed = new TaskCompletionSource<int>(); using (var scheduler = new EventLoopScheduler()) { Assert.AreEqual(0, scheduler.CurrentCount()); var maxCount = Environment.ProcessorCount; using (Enumerable.Range(1, maxCount) .Select(_ => scheduler.SchedulePeriodic(TimeSpan.Zero, () => { var count = scheduler.CurrentCount(); if (count > maxCount) failed.SetResult(count); })) .Aggregate( new CompositeDisposable(), (c, d) => { c.Add(d); return c; })) { if (failed.Task.Wait(TimeSpan.FromSeconds(10))) { Assert.Fail("Semaphore count is too high: {0}", failed.Task.Result); } } } }
/// <summary> /// Initializes a new instance of the <see cref="LogEntryService"/> class. /// </summary> /// <param name="logger">The logger.</param> public LogEntryService(ILogger logger) { _logger = logger; var scheduler = new EventLoopScheduler(); //expire old items var timeExpirer = _source.AutoRemove(le => { return TimeSpan.FromSeconds(le.Level == LogLevel.Debug ? 5 : 60); },TimeSpan.FromSeconds(5), TaskPoolScheduler.Default) .Subscribe(removed => { logger.Debug("{0} log items have been automatically removed",removed.Count()); }); // var expirer = _source.ExpireFromSource(50).Subscribe(); //populate the source cache from the logger observable var loader = RxAppender.LogEntryObservable .ObserveOn(scheduler) .Subscribe(item => _source.AddOrUpdate(item)); _disposer = Disposable.Create(() => { timeExpirer.Dispose(); // expirer.Dispose(); scheduler.Dispose(); loader.Dispose(); _source.Dispose(); }); _logger.Info("Log cache has been constructed"); }
public static IEnumerable<IObservable<PlayerData>> computePlayerData(IObservable<SensorData> src) { var scheduler = new EventLoopScheduler(); return MetaData .PLAYER_MAP .Select((KeyValuePair<string, List<int>> keyValue, int index) => { var pt = PerformanceTest.ptArray[index]; var sensorList = keyValue.Value; //The list of sensors attached to this player var sensorStreamList = sensorList.Select((int sensor_id) => { return src//.ObserveOn(scheduler) .Where(ss => ss.sensor_id == sensor_id) .Once(MetaData.getDefaultSensorDataWithSensorID(sensor_id)); }); return Observable .Zip(sensorStreamList) //If AvgProcessorStatus==true, then compute performance metrics for AverageProcessor. .DoIf(() => PerformanceTest.AvgProcessorStatus, d => pt.recordTime()) .Select(returnPlayerData) .Where(data => !String.IsNullOrEmpty(data.player_name)) //compute time taken to produce a PlayerData sample from list of updated sensor values. .DoIf(() => PerformanceTest.AvgProcessorStatus, d => pt.computeMetrics()); }); }
public virtual void Dispose() { if (m_eventLoopScheduler != null) m_eventLoopScheduler.Dispose(); m_eventLoopScheduler = null; Console.WriteLine("disposed Transport " + Name); }
static void Main() { var eventLoop = new EventLoopScheduler(); using (var requests = new HttpServer("http://127.0.0.1:987/", eventLoop)) { requests.GET("app.js") .Subscribe(r => r.Respond(new StaticFileResponse("app.js"))); requests.GET("index.html") .Subscribe(r => r.Respond(new StaticFileResponse("index.html"))); var messageStream = requests.POST("send") .Select(r => { string message; using(var sr = new StreamReader(r.Request.InputStream)) { message = sr.ReadToEnd(); } r.Respond(201); return message; }).Publish().RefCount(); requests.POST("wait") .SelectMany(subscriber => messageStream.Take(1), (subscriber, message) => new {subscriber, message}) .Subscribe(kp => kp.subscriber.Respond(new StringResponse(kp.message))); Console.ReadLine(); } }
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; }
public void EventLoop_ScheduleAction() { var ran = false; var gate = new Semaphore(0, 1); var el = new EventLoopScheduler(); el.Schedule(() => { ran = true; gate.Release(); }); Assert.IsTrue(gate.WaitOne(TimeSpan.FromSeconds(2))); Assert.IsTrue(ran); }
public virtual void Init(string path) { LocalPath = path; Console.WriteLine("starting Transport " + Name); m_eventLoopScheduler = new EventLoopScheduler(start => new Thread(start) { IsBackground = true, Name = Name, }); }
public PublisherManager(MessageBus messageBus) { _messageBus = messageBus; var scheduler = new EventLoopScheduler(); _messageBus.SendableMulticastDataMessages.SubscribeOn(scheduler).Subscribe(PublishMulticastMessage); _messageBus.SendableUnicastDataMessages.SubscribeOn(scheduler).Subscribe(PublishUnicastMessage); _messageBus.ClosedInteractors.SubscribeOn(scheduler).Subscribe(RemoveInteractor); _messageBus.FaultedInteractors.SubscribeOn(scheduler).Subscribe(FaultedInteractor); }
public WikiSite(WikiConfig config, MasterRepository masterRepository, ISourceWatcher sourceWatcher, IPageCache pageCache) { wikiConfig = config; repository = masterRepository; watcher = sourceWatcher; generator = new WikiGenerator(wikiConfig.Convertor, wikiConfig.RootWikiPath, pageCache); siteGeneratorScheduler = new EventLoopScheduler(threadStart => new Thread(threadStart) { Name = "SiteGenerator" }); }
public ExecutionContextServiceServant() { _state = LifeCycleState.CREATED_STATE; _timeSpan = TimeSpan.FromSeconds(1); _isRunning = false; _state = LifeCycleState.INACTIVE_STATE; ExecutionContextScheduler = new EventLoopScheduler(); _profile = new ExecutionContextProfile(); }
public SystemPinger(string computerName) { var pollingPeriod = TimeSpan.FromSeconds(PingFrequencySeconds); var scheduler = new EventLoopScheduler(ts => new Thread(ts) { Name = "DatabasePoller" }); var query = Observable.Timer(pollingPeriod, scheduler) .SelectMany(_ => Ping(computerName).ToObservable()) .Repeat(); //Loop on success PingSource = query; }
public void EventLoop_ArgumentChecking() { var el = new EventLoopScheduler(); ReactiveAssert.Throws<ArgumentNullException>(() => new EventLoopScheduler(null)); ReactiveAssert.Throws<ArgumentNullException>(() => el.Schedule<int>(42, default(Func<IScheduler, int, IDisposable>))); ReactiveAssert.Throws<ArgumentNullException>(() => el.Schedule<int>(42, DateTimeOffset.Now, default(Func<IScheduler, int, IDisposable>))); ReactiveAssert.Throws<ArgumentNullException>(() => el.Schedule<int>(42, TimeSpan.Zero, default(Func<IScheduler, int, IDisposable>))); ReactiveAssert.Throws<ArgumentNullException>(() => el.SchedulePeriodic(42, TimeSpan.FromSeconds(1), default(Func<int, int>))); ReactiveAssert.Throws<ArgumentOutOfRangeException>(() => el.SchedulePeriodic(42, TimeSpan.FromSeconds(-1), _ => _)); }
public NotificationManager(MessageBus messageBus) { _messageBus = messageBus; var scheduler = new EventLoopScheduler(); _messageBus.NotificationRequests.SubscribeOn(scheduler).Subscribe(HandleNotificationRequest); _messageBus.ForwardedSubscriptionRequests.SubscribeOn(scheduler).Subscribe(NotifyListenersOnTopic); _messageBus.ClosedInteractors.SubscribeOn(scheduler).Subscribe(RemoveInteractor); _messageBus.FaultedInteractors.SubscribeOn(scheduler).Subscribe(FaultedInteractor); }
public Market(IObservable<Interactor> listenerObservable) { _subscriptionManager = new SubscriptionManager(_messageBus); _publisherManager = new PublisherManager(_messageBus); _notificationManager = new NotificationManager(_messageBus); var scheduler = new EventLoopScheduler(); _listenerDisposable = listenerObservable.SubscribeOn(scheduler).Subscribe(AddInteractor); _messageBus.ClosedInteractors.SubscribeOn(scheduler).Subscribe(RemoveInteractor); _messageBus.FaultedInteractors.SubscribeOn(scheduler).Subscribe(FaultedInteractor); }
public void EventLoop_DifferentThread() { var id = default(int); var gate = new Semaphore(0, 1); var el = new EventLoopScheduler(); el.Schedule(() => { id = Thread.CurrentThread.ManagedThreadId; gate.Release(); }); Assert.IsTrue(gate.WaitOne(TimeSpan.FromSeconds(2))); Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, id); }
public SubscriptionManager(MessageBus messageBus) { _messageBus = messageBus; var scheduler = new EventLoopScheduler(); _messageBus.SubscriptionRequests.SubscribeOn(scheduler).Subscribe(HandleSubscriptionRequest); _messageBus.NewNotificationRequests.SubscribeOn(scheduler).Subscribe(ForwardSubscriptionRequests); _messageBus.PublishedMulticastDataMessages.SubscribeOn(scheduler).Subscribe(HandleMulticastDataMessage); _messageBus.PublishedUnicastDataMessages.SubscribeOn(scheduler).Subscribe(HandleUnicastDataMessage); _messageBus.StalePublishers.SubscribeOn(scheduler).Subscribe(HandleStalePublisher); _messageBus.ClosedInteractors.SubscribeOn(scheduler).Subscribe(RemoveInteractor); _messageBus.FaultedInteractors.SubscribeOn(scheduler).Subscribe(FaultedInteractor); }
public GrapevineSender(ZmqContext context, string address, IMessageSerializer serializer) { _serializer = serializer; _scheduler = new EventLoopScheduler(); _socket = context.CreateSocket(SocketType.PUB); _socket.Connect(address); _messages = new Subject<ZmqMessage>(); _messageDispatcher = _messages .SubscribeOn(_scheduler) .ObserveOn(_scheduler) .Subscribe(msg => _socket.SendMessage(msg)); }
public void EventLoop_ScheduleOrderedActions() { var results = new List<int>(); var gate = new Semaphore(0, 1); var el = new EventLoopScheduler(); el.Schedule(() => results.Add(0)); el.Schedule(() => { results.Add(1); gate.Release(); }); Assert.IsTrue(gate.WaitOne(TimeSpan.FromSeconds(2))); results.AssertEqual(0, 1); }
public static void Run() { Console.WriteLine("Start testing on threadId {0} at {1}", Util.GetTid(), DateTime.Now); var scheduler = new EventLoopScheduler(); scheduler.Schedule(() => Console.WriteLine("Do 1 on theadId {0} at {1}", Util.GetTid(), DateTime.Now)); scheduler.Schedule(() => { Console.WriteLine("Do 2 on theadId {0} at {1}", Util.GetTid(), DateTime.Now); Task.Delay(TimeSpan.FromSeconds(1)).Wait(); }); scheduler.Schedule(() => Console.WriteLine("Do 3 on theadId {0} at {1}", Util.GetTid(), DateTime.Now)); scheduler.Schedule(() => Console.WriteLine("Do 4 on theadId {0} at {1}", Util.GetTid(), DateTime.Now)); Console.WriteLine("Wait..."); Task.Delay(TimeSpan.FromSeconds(2)).Wait(); }
/// <summary> /// Extension method on AFDataPipe to create an IObservable. A subscription to the underlying AFDataPipe is made. /// An EventLoopScheduler is set up to poll GetObserverEvents at a configurable interval. /// The Publish/RefCount construct is used to handle subscription side-effects and share the underlying AFDataPipe subscription /// with mulitple observers. /// See http://www.introtorx.com/content/v1.0.10621.0/14_HotAndColdObservables.html for Publish/RefCount documentation. /// See http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx for the Publish/RefCount use case. /// See http://stackoverflow.com/questions/14396449/why-are-subjects-not-recommended-in-net-reactive-extensions for EventLoopScheduler and recursion idea. /// See http://www.zerobugbuild.com/?p=259 for recursive scheduling idea. /// </summary> /// <param name="dataPipe"></param> /// <param name="seconds">Number of seconds to wait before calling GetObserverEvents</param> /// <returns></returns> public static IObservable<AFDataPipeEvent> CreateObservable(this AFDataPipe dataPipe, double seconds = 1) { TimeSpan interval = TimeSpan.FromSeconds(seconds); return Observable.Create<AFDataPipeEvent>(observer => { IDisposable dpToken = dataPipe.Subscribe(observer); EventLoopScheduler scheduler = new EventLoopScheduler(); IDisposable scheduleToken = scheduler.Schedule(dpToken, interval, (state, recurse) => { try { bool hasMoreEvents = true; while (hasMoreEvents) { dataPipe.GetObserverEvents(out hasMoreEvents); } recurse(dpToken, interval); } catch (Exception ex) { observer.OnError(ex); } }); return Disposable.Create(() => { scheduleToken.Dispose(); scheduler.Dispose(); dpToken.Dispose(); }); }) .Publish() .RefCount(); }
private static void SubscribeOnConfusion() { Demo.DisplayHeader("SubscribeOn operator - running the unsubscrition on another schdeudler might be confusing since it can take long time to complete"); var eventLoopScheduler = new EventLoopScheduler(); var subscription = Observable.Interval(TimeSpan.FromSeconds(1)) .Do(x => Console.WriteLine("Inside Do")) .SubscribeOn(eventLoopScheduler) .SubscribeConsole(); eventLoopScheduler.Schedule(1, (s, state) => { Console.WriteLine("Before sleep"); Thread.Sleep(TimeSpan.FromSeconds(3)); Console.WriteLine("After sleep"); return Disposable.Empty; }); subscription.Dispose(); Console.WriteLine("Subscription disposed"); }
static RxApp() { // Default name for the field backing the "Foo" property => "_Foo" // This is used for ReactiveObject's RaiseAndSetIfChanged mixin GetFieldNameForPropertyNameFunc = new Func <string, string>(x => "_" + x); #if WP7 TaskpoolScheduler = new EventLoopScheduler(); #elif WP8 //TaskpoolScheduler = Scheduler.TaskPool; TaskpoolScheduler = Scheduler.ThreadPool; #elif SILVERLIGHT || DOTNETISOLDANDSAD TaskpoolScheduler = Scheduler.ThreadPool; #elif WINRT TaskpoolScheduler = System.Reactive.Concurrency.ThreadPoolScheduler.Default; #else TaskpoolScheduler = Scheduler.TaskPool; #endif DefaultExceptionHandler = Observer.Create <Exception>(ex => { // NB: If you're seeing this, it means that an // ObservableAsPropertyHelper or the CanExecute of a // ReactiveCommand ended in an OnError. Instead of silently // breaking, ReactiveUI will halt here if a debugger is attached. if (Debugger.IsAttached) { Debugger.Break(); } RxApp.DeferredScheduler.Schedule(() => { throw new Exception( "An OnError occurred on an object (usually ObservableAsPropertyHelper) that would break a binding or command. To prevent this, Subscribe to the ThrownExceptions property of your objects", ex); }); }); MessageBus = new MessageBus(); LoggerFactory = t => new DebugLogger(); RxApp.Register(typeof(INPCObservableForProperty), typeof(ICreatesObservableForProperty)); RxApp.Register(typeof(IRNPCObservableForProperty), typeof(ICreatesObservableForProperty)); RxApp.Register(typeof(POCOObservableForProperty), typeof(ICreatesObservableForProperty)); RxApp.Register(typeof(PropertyBinderImplementation), typeof(IPropertyBinderImplementation)); RxApp.Register(typeof(NullDefaultPropertyBindingProvider), typeof(IDefaultPropertyBindingProvider)); RxApp.Register(typeof(EqualityTypeConverter), typeof(IBindingTypeConverter)); RxApp.Register(typeof(StringConverter), typeof(IBindingTypeConverter)); #if !SILVERLIGHT && !WINRT RxApp.Register(typeof(ComponentModelTypeConverter), typeof(IBindingTypeConverter)); #endif var namespaces = attemptToEarlyLoadReactiveUIDLLs(); namespaces.ForEach(ns => { #if WINRT var assm = typeof(RxApp).GetTypeInfo().Assembly; #else var assm = Assembly.GetExecutingAssembly(); #endif var fullName = typeof(RxApp).AssemblyQualifiedName; var targetType = ns + ".ServiceLocationRegistration"; fullName = fullName.Replace("ReactiveUI.RxApp", targetType); fullName = fullName.Replace(assm.FullName, assm.FullName.Replace("ReactiveUI", ns)); var registerTypeClass = Reflection.ReallyFindType(fullName, false); if (registerTypeClass != null) { var registerer = (IWantsToRegisterStuff)Activator.CreateInstance(registerTypeClass); registerer.Register(); } }); if (InUnitTestRunner()) { LogHost.Default.Warn("*** Detected Unit Test Runner, setting Scheduler to Immediate ***"); LogHost.Default.Warn("If we are not actually in a test runner, please file a bug\n"); DeferredScheduler = Scheduler.Immediate; } else { LogHost.Default.Info("Initializing to normal mode"); } if (DeferredScheduler == null) { LogHost.Default.Error("*** ReactiveUI.Xaml DLL reference not added - using Event Loop *** "); LogHost.Default.Error("Add a reference to ReactiveUI.Xaml if you're using WPF / SL5 / WP7 / WinRT"); LogHost.Default.Error("or consider explicitly setting RxApp.DeferredScheduler if not"); RxApp.DeferredScheduler = new EventLoopScheduler(); } }
public Mediator() { _aggregator = new EventAggregator(); _scheduler = new EventLoopScheduler(); }
public void RegisterMemoizedFunctionSmokeTest() { var input = new[] { 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 }; var output = new[] { 5, 5, 5, 5, 5, 10, 10, 10, 10, 10 }; var sched = new EventLoopScheduler(); var results = new List<Timestamped<int>>(); var start = sched.Now; sched.With(_ => { var fixture = new ReactiveAsyncCommand(null, 5, sched); fixture.RegisterMemoizedFunction(x => { Thread.Sleep(1000); return ((int) x) * 5; }, 50, null, sched) .Timestamp() .Subscribe(x => results.Add(x)); Assert.True(fixture.CanExecute(1)); foreach (var i in input) { Assert.True(fixture.CanExecute(i)); fixture.Execute(i); } Thread.Sleep(2500); }); Assert.Equal(10, results.Count); results.Select(x => x.Timestamp - start) .Run(x => { }); output.AssertAreEqual(results.Select(x => x.Value)); Assert.False(results.Any(x => x.Timestamp - start > new TimeSpan(0, 0, 3))); }
public void MakeSureMemoizedReleaseFuncGetsCalled() { //Assert.True(false, "When an item gets evicted from the cache before it has a chance to complete, it deadlocks. Fix it."); var input = new[] { 1, 1, 2, 2, 1, 1, 3, 3 }; var sched = new EventLoopScheduler(); var fixture = new ReactiveAsyncCommand(); var results = new List<Timestamped<int>>(); var released = new List<int>(); fixture.RegisterMemoizedFunction(x => { Thread.Sleep(250); return ((int)x) * 5; }, 2, x => released.Add(x), sched) .Timestamp() .DebugObservable() .Subscribe(x => results.Add(x)); Assert.True(fixture.CanExecute(1)); var start = DateTimeOffset.Now; foreach(var i in input) { Assert.True(fixture.CanExecute(i)); fixture.Execute(i); } Thread.Sleep(1000); this.Log().Info("Timestamp Deltas"); results.Select(x => x.Timestamp - start) .Run(x => this.Log().Info(x)); this.Log().Info("Release list"); released.Run(x => this.Log().Info(x)); Assert.True(results.Count == 8); Assert.True(released.Count == 1); Assert.True(released[0] == 2*5); }
private ForegroundScheduler() { this.inner = new EventLoopScheduler(this.CreateThread); }
public VisualRxPublishersSettings() { Scheduler = new EventLoopScheduler(); }
static RxApp() { #if DEBUG LoggerFactory = (prefix) => new StdErrLogger(prefix) { CurrentLogLevel = LogLevel.Info }; #else LoggerFactory = (prefix) => new NullLogger(prefix); #endif // Default name for the field backing the "Foo" property => "_Foo" // This is used for ReactiveObject's RaiseAndSetIfChanged mixin GetFieldNameForPropertyNameFunc = new Func <string, string>(x => "_" + x); if (InUnitTestRunner()) { Console.Error.WriteLine("*** Detected Unit Test Runner, setting Scheduler to Immediate ***"); Console.Error.WriteLine("If we are not actually in a test runner, please file a bug\n"); DeferredScheduler = Scheduler.Immediate; #if DEBUG LoggerFactory = (prefix) => new StdErrLogger(prefix) { CurrentLogLevel = LogLevel.Debug }; #else LoggerFactory = (prefix) => new StdErrLogger(prefix) { CurrentLogLevel = LogLevel.Info }; #endif #if FALSE DefaultUnitTestRecoveryResult = RecoveryOptionResult.FailOperation; CustomErrorPresentationFunc = new Func <UserException, RecoveryOptionResult>(e => { Console.Error.WriteLine("Presenting Error: '{0}'", e.LocalizedFailureReason); Console.Error.WriteLine("Returning default result: {0}", DefaultUnitTestRecoveryResult); return(DefaultUnitTestRecoveryResult); }); #endif } else { Console.Error.WriteLine("Initializing to normal mode"); #if IOS // XXX: This should be an instance of NSRunloopScheduler DeferredScheduler = new EventLoopScheduler(); #else DeferredScheduler = findDispatcherScheduler(); #endif } #if WINDOWS_PHONE TaskpoolScheduler = new EventLoopScheduler(); #elif SILVERLIGHT || DOTNETISOLDANDSAD TaskpoolScheduler = Scheduler.ThreadPool; #else // NB: In Rx 1.0, Tasks are being scheduled synchronously - i.e. // they're not being run on the Task Pool on other threads. Use // the old-school Thread pool instead. TaskpoolScheduler = Scheduler.ThreadPool; //TaskpoolScheduler = Scheduler.TaskPool; #endif MessageBus = new MessageBus(); }
public void EventLoop_Now() { var res = new EventLoopScheduler().Now - DateTime.Now; Assert.True(res.Seconds < 1); }
public GrapevineReceiver(ZmqContext context, string address, IMessageSerializer serializer) { _scheduler = new EventLoopScheduler(); _socket = context.CreateSocket(SocketType.SUB); _messages = ListenForMessages(context, address, serializer); }
private static int CurrentCount(this EventLoopScheduler scheduler) { return(((SemaphoreSlim)semaphore.GetValue(scheduler)).CurrentCount); }
public void ShouldCorrectlyPublishAndSubscribeToMulipleMultiplexedTopics() { const string brokerUri = "tcp://localhost:61616"; const string topicName1 = "Obvs.Tests.ShouldCorrectlyPublishAndSubscribeToMulipleMultiplexedTopics1"; const string topicName2 = "Obvs.Tests.ShouldCorrectlyPublishAndSubscribeToMulipleMultiplexedTopics2"; IMessagePropertyProvider <IMessage> getProperties = new DefaultPropertyProvider <IMessage>(); IConnectionFactory connectionFactory = new ConnectionFactory(brokerUri); var lazyConnection = new Lazy <IConnection>(() => { var conn = connectionFactory.CreateConnection(); conn.Start(); return(conn); }); var scheduler = new EventLoopScheduler(); IMessagePublisher <IMessage> publisher1 = new MessagePublisher <IMessage>( lazyConnection, new ActiveMQTopic(topicName1), new JsonMessageSerializer(), getProperties, scheduler); IMessagePublisher <IMessage> publisher2 = new MessagePublisher <IMessage>( lazyConnection, new ActiveMQTopic(topicName2), new JsonMessageSerializer(), getProperties, scheduler); IMessageDeserializer <IMessage>[] deserializers = { new JsonMessageDeserializer <TestMessage>(), new JsonMessageDeserializer <TestMessage2>() }; IMessageSource <IMessage> source = new MergedMessageSource <IMessage>(new[] { new MessageSource <IMessage>( lazyConnection, deserializers, new ActiveMQTopic(topicName1)), new MessageSource <IMessage>( lazyConnection, deserializers, new ActiveMQTopic(topicName2)) }); source.Messages.Subscribe(Console.WriteLine); publisher1.PublishAsync(new TestMessage { Id = 1234 }); publisher1.PublishAsync(new TestMessage2 { Id = 4567 }); publisher2.PublishAsync(new TestMessage { Id = 8910 }); publisher2.PublishAsync(new TestMessage2 { Id = 1112 }); Thread.Sleep(TimeSpan.FromSeconds(3)); }
public void Stopwatch() { using var el = new EventLoopScheduler(); StopwatchTest.Run(el); }
public static IDisposable SubscribeToLatestOnBGThread <TSource>(this IObservable <TSource> subject , Action <TSource> onNext, EventLoopScheduler scheduler = null, Action <Exception> onError = null, Action onCompleted = null) { return(subject.Latest() .ToObservable(scheduler ?? BGTreadSchedulerFactory()) .Subscribe(onNext, onError ?? (exc => { }), onCompleted ?? (() => { }))); }