public Outputs Create(Inputs inputs) 
 {
     EventLoop<Fuel> eStart = new EventLoop<Fuel>();
     Fill fi = new Fill(inputs.EClearSale.Map(u => Unit.UNIT),
                        inputs.EFuelPulses, inputs.Calibration,
                        inputs.Price1, inputs.Price2, inputs.Price3,
                        eStart);
     NotifyPointOfSale np = new NotifyPointOfSale(
             new LifeCycle(inputs.ENozzle1,
                           inputs.ENozzle2,
                           inputs.ENozzle3),
             inputs.EClearSale,
             fi);
     eStart.Loop(np.EStart);
     BehaviorLoop<bool> keypadActive = new BehaviorLoop<bool>();
     Keypad ke = new Keypad(inputs.EKeypad,
                            inputs.EClearSale,
                            keypadActive);
     Preset pr = new Preset(ke.Value,
                            fi,
                            np.FuelFlowing,
                            np.FillActive.Map(o => o.IsPresent));
     keypadActive.Loop(pr.KeypadActive);
     return new Outputs()
         .SetDelivery(pr.Delivery)
         .SetSaleCostLcd(fi.DollarsDelivered.Map(q => Formatters.FormatSaleCost(q)))
         .SetSaleQuantityLcd(fi.LitersDelivered.Map(q => Formatters.FormatSaleQuantity(q)))
         .SetPriceLcd1(ShowDollarsPump.PriceLCD(np.FillActive, fi.Price, Fuel.ONE, inputs))
         .SetPriceLcd2(ShowDollarsPump.PriceLCD(np.FillActive, fi.Price, Fuel.TWO, inputs))
         .SetPriceLcd3(ShowDollarsPump.PriceLCD(np.FillActive, fi.Price, Fuel.THREE, inputs))
         .SetSaleComplete(np.ESaleComplete)
         .SetPresetLcd(ke.Value.Map(v => Formatters.FormatSaleCost((double)v)))
         .SetBeep(np.EBeep.Merge(ke.EBeep));
 }
Example #2
0
 public Outputs Create(Inputs inputs) 
 {
     EventLoop<Fuel> eStart = new EventLoop<Fuel>();
     Fill fi = new Fill(
                       inputs.EClearSale.Map(u => Unit.UNIT),
                       inputs.EFuelPulses, inputs.Calibration,
                       inputs.Price1, inputs.Price2, inputs.Price3,
                       eStart);
     NotifyPointOfSale np = new NotifyPointOfSale(
             new LifeCycle(inputs.ENozzle1,
                           inputs.ENozzle2,
                           inputs.ENozzle3),
             inputs.EClearSale,
             fi);
     eStart.Loop(np.EStart);
     return new Outputs()
         .SetDelivery(np.FuelFlowing.Map(
             of =>
                 of.Equals(Optional<Fuel>.Of(Fuel.ONE))   ? Delivery.FAST1 :
                 of.Equals(Optional<Fuel>.Of(Fuel.TWO))   ? Delivery.FAST2 :
                 of.Equals(Optional<Fuel>.Of(Fuel.THREE)) ? Delivery.FAST3 : 
                                                      Delivery.OFF))
         .SetSaleCostLcd(fi.DollarsDelivered.Map(
                 q => Formatters.FormatSaleCost(q)))
         .SetSaleQuantityLcd(fi.LitersDelivered.Map(
                 q => Formatters.FormatSaleQuantity(q)))
         .SetPriceLcd1(ShowDollarsPump.PriceLCD(np.FillActive, fi.Price,
                 Fuel.ONE, inputs))
         .SetPriceLcd2(ShowDollarsPump.PriceLCD(np.FillActive, fi.Price,
                 Fuel.TWO, inputs))
         .SetPriceLcd3(ShowDollarsPump.PriceLCD(np.FillActive, fi.Price,
                 Fuel.THREE, inputs))
         .SetBeep(np.EBeep)
         .SetSaleComplete(np.ESaleComplete);
 }
        public override void UponReceiptBy(EventLoop eventLoop, string senderAddress)
        {
            // Convert all parameters to their original type (otherwise it'd be hard to distinguish between int32 and int64, for example)
            for (int i = 0; i < parameters.Length; i++)
                parameters[i] = this.ConvertToType(parameters[i], parameterTypes[i]);

            eventLoop.discoveryManager.OnNetworkRemoteMethodInvocationReceived(this.objectReference, this.futureReference, senderAddress, selector, parameters);
        }
Example #4
0
 /// <summary>
 /// Main program method
 /// </summary>
 /// <param name="args"></param>
 public static void Main(string[] args)
 {
     var eventLoop = new EventLoop();
     var cursorManager = new CursorManager();
     eventLoop.UpHandler += cursorManager.OnUp;
     eventLoop.RightHandler += cursorManager.OnRight;
     eventLoop.DownHandler += cursorManager.OnDown;
     eventLoop.LeftHandler += cursorManager.OnLeft;
     eventLoop.Run();
 }
Example #5
0
 public static void Main(string[] args)
 {
     var eventLoop = new EventLoop();
     var moveCursor = new MoveCursor();
     eventLoop.LeftHandler += moveCursor.Left;
     eventLoop.RightHandler += moveCursor.Right;
     eventLoop.UpHandler += moveCursor.Up;
     eventLoop.DownHandler += moveCursor.Down;
     eventLoop.Run();
 }
        private static void Test(Action <SynchronizationContext> action)
        {
            var done = false;

            EventLoop.Run(() =>
            {
                action(SynchronizationContext.Current);
                done = true;
            });
            Assert.True(done);
        }
Example #7
0
        protected override void ScheduleSocketRead()
        {
            var operation = ReadOperation;
            var pending   = Socket.ReceiveAsync(operation);

            if (!pending)
            {
                // todo: potential allocation / non-static field?
                EventLoop.Execute(ReadCompletedSyncCallback, Unsafe, operation);
            }
        }
Example #8
0
        protected void LoadView(string view, Action <Exception, string> callback)
        {
            var deUrled  = view.Replace('/', '\\').TrimStart('\\');
            var viewFile = Path.Combine(ViewsRoot, deUrled);

            if (!System.IO.File.Exists(viewFile))
            {
                throw new FileNotFoundException("View not found.");
            }
            FileSystem.File.ReadAllText(viewFile, (ex, text) => EventLoop.Pend(() => callback(ex, text)));
        }
Example #9
0
        /// <summary>
        /// The main routine in which a connection is made and maintained.
        /// This function will only return once the EventLoop is stopped,
        /// which happens when the connection ends.
        /// </summary>
        public void Run()
        {
            try
            {
                // Keep these SDK objects available all the time the session is running.
                Viewer      = new Viewer();
                FrameBuffer = new FrameBuffer(Viewer);

                SetUpCallbacks(Viewer);

                // Begin the connection to the Server.

                if (CurrentCanvasSize == null)
                {
                    CurrentCanvasSize = new Vector2Int(1920, 1080);
                }

                UpdateFrameBufferToCanvasSize();

                // Make a Direct TCP connecticon.
                NewStatus($"Connecting to host address: {TcpAddress} port: {TcpPort}");
                using (DirectTcpConnector tcpConnector = new DirectTcpConnector())
                {
                    tcpConnector.Connect(TcpAddress, TcpPort, Viewer.GetConnectionHandler());
                }

                // Run the SDK's event loop.  This will return when any thread
                // calls EventLoop.Stop(), allowing this ViewerSession to stop.
                RunningSession = this;
                EventLoop.Run();
            }
            catch (Exception e)
            {
                Console.WriteLine("SDK error: {0}: {1}", e.GetType().Name, e.Message);

                // Handle the implied disconnect (or failed to connect) and show the exception message as a status
                DisconnectReason = e.GetType().Name + ": " + e.Message;
            }
            finally
            {
                RunningSession = null;

                // Dispose of the SDK objects.
                FrameBuffer?.Dispose();
                FrameBuffer = null;

                // If the viewer is still connected, this drops the connection.
                Viewer?.Dispose();
                Viewer = null;

                // Notify that the session is finished and another may be enqueued.
                ReportDisconnection();
            }
        }
Example #10
0
 public override void Dispose(bool disposing)
 {
     if (!WasDisposed && disposing && Listener != null)
     {
         Stop();
         Listener.Dispose();
         EventLoop.Dispose();
     }
     IsActive    = false;
     WasDisposed = true;
 }
Example #11
0
 private static void Main(string[] args)
 {
     Routing.Add("/Test", typeof(TestController), "Test");
     Routing.Add("/Foo/:foo", typeof(TestController), "Foo");
     EventLoop.Start(() => Server.Create()
                     .Use(RazorView.Default)
                     .Use(Routing.Handler)
                     .Use(Static.Directory("/public"))
                     .Listen("http://*:1337/"));
     Console.ReadKey();
 }
Example #12
0
 public void Process(Func <bool> terminate, bool exitAtEndOfStream, bool includeImmediate)
 {
     try
     {
         EventLoop.Run(() => LoopBody(terminate, exitAtEndOfStream, includeImmediate));
     }
     catch (Exception e)
     {
         Logger.Error("Application Terminated Due To Error: " + e);
     }
 }
Example #13
0
        public void EventLoopUnhandledPostExceptionWorks()
        {
            var gotIt = false;

            EventLoop.Run(async() =>
            {
                EventLoop.UnhandledException += ex => { gotIt = true; };
                await Throw(1);
            });
            Assert.True(gotIt);
        }
Example #14
0
        public void EventLoopRunsAsync()
        {
            var i = 0;

            EventLoop.Run(async() =>
            {
                await Task.Yield();
                i++;
            });
            Assert.Equal(1, i);
        }
Example #15
0
        private static WorkingLine CreateWorkingLine(int worker)
        {
            const string TAG = "Test";
            var          el  = new EventLoop("Test");
            var          wf  = new TestWorkerFactory();
            var          wl  = new WorkingLine(el, TAG, wf, worker: worker);

            Assert.AreEqual(wf, wl.WorkerFactory);
            Assert.AreEqual(worker, wl.Worker);
            Assert.AreEqual(wl.Worker, wl.WorkerThreads.Count);
            return(wl);
        }
Example #16
0
        private static void Main()
        {
            var game      = GameInitializer.LoadGameWithSpecifiedMapWriterFromFile("ConsoleGame.Maps.GoodMap.txt", new ConsoleMapWriter());
            var eventLoop = new EventLoop();

            eventLoop.DownHandler  += game.OnDown;
            eventLoop.UpHandler    += game.OnUp;
            eventLoop.RightHandler += game.OnRight;
            eventLoop.LeftHandler  += game.OnLeft;

            eventLoop.Run();
        }
Example #17
0
        public void EventLoopTests()
        {
            EventLoop el = new EventLoop();

            el.RegisterAction(() => { System.Diagnostics.Debug.WriteLine("Hello World"); });
            el.RegisterAction(() => { System.Console.WriteLine("Hello World"); });

            Thread t = new Thread(new ThreadStart(el.Start));

            t.Start();
            el.Close();
        }
Example #18
0
        static void Main(string[] args)
        {
            var eventLoop = new EventLoop();
            var game      = new Game();

            eventLoop.LeftHandler  += game.OnLeft;
            eventLoop.RightHandler += game.OnRight;
            eventLoop.UpHandler    += game.OnUp;
            eventLoop.DownHandler  += game.OnDown;

            eventLoop.Run();
        }
Example #19
0
        static void Main(string[] args)
        {
            var eventLoop = new EventLoop();
            var cursor    = new CursorControle();

            eventLoop.LeftHandler  += cursor.OnLeft;
            eventLoop.RightHandler += cursor.OnRight;
            eventLoop.UpHandler    += cursor.OnUp;
            eventLoop.DownHandler  += cursor.OnDown;

            eventLoop.Run();
        }
Example #20
0
        static void Main(string[] args)
        {
            var eventLoop     = new EventLoop();
            var smileyHandler = new QuestionHandler("map.txt");

            eventLoop.LeftPressed  += smileyHandler.LeftMovement;
            eventLoop.RightPressed += smileyHandler.RightMovement;
            eventLoop.UpPressed    += smileyHandler.UpMovement;
            eventLoop.DownPressed  += smileyHandler.DownMovement;

            eventLoop.Run();
        }
Example #21
0
        public void ThrowIfDisposed()
        {
            // arrange
            var loop = new EventLoop();

            // act
            loop.Start(() => { });
            loop.Dispose();

            // assert
            Assert.That(() => loop.Start(() => { }), Throws.InstanceOf <ObjectDisposedException>());
        }
Example #22
0
        protected override void DoBeginRead()
        {
            if (_readInProgress)
            {
                return;
            }

            var pipeline      = Pipeline;
            var inboundBuffer = _inboundBuffer;

            if (!inboundBuffer.Any())
            {
                _readInProgress = true;
                return;
            }

            var stackDepth = _stackDepth.Value;

            if (stackDepth < MAX_READER_STACK_DEPTH)
            {
                _stackDepth.Value = stackDepth + 1;
                try
                {
                    while (true)
                    {
                        if (inboundBuffer.Count == 0)
                        {
                            break;
                        }
                        var received = inboundBuffer.Dequeue();
                        pipeline.FireChannelRead(received);
                    }
                    pipeline.FireChannelReadComplete();
                }
                finally
                {
                    _stackDepth.Value = stackDepth;
                }
            }
            else
            {
                try
                {
                    EventLoop.Execute(_readTask);
                }
                catch (Exception)
                {
                    ReleaseInboundBuffers();
                    throw;
                }
            }
        }
        /// <summary>
        ///     Creates new instance of <see cref="BufferedLinkLogger" />
        /// </summary>
        /// <param name="undelyingLogger">Underlying logger to write messages</param>
        /// <param name="maxMessages">Maximum number of messages in buffer, after buffer overflow it will blocks next writes</param>
        public BufferedLinkLogger(ILinkLogger undelyingLogger, int? maxMessages = 1000)
        {
            if (undelyingLogger == null)
                throw new ArgumentNullException(nameof(undelyingLogger));
            if (maxMessages <= 0)
                throw new ArgumentException("Must be greater than zero", nameof(maxMessages));

            UnderlyingLogger = undelyingLogger;

            _eventLoop = maxMessages == null
                ? new EventLoop(EventLoop.DisposingStrategy.Wait)
                : new EventLoop(maxMessages.Value, EventLoop.DisposingStrategy.Wait);
        }
Example #24
0
File: Sql.cs Project: benlesh/ALE
        private void EndExecuteReader(IAsyncResult result)
        {
            var state = (ExecuteReaderState)result.AsyncState;

            try
            {
                var reader = state.Command.EndExecuteReader(result);
                EventLoop.Pend(() => state.Callback(null, reader));
            } catch (Exception ex)
            {
                EventLoop.Pend(() => state.Callback(ex, null));
            }
        }
Example #25
0
File: Sql.cs Project: benlesh/ALE
        public void ExecuteNonQueryCallback(IAsyncResult result)
        {
            var state = (ExecuteNonQueryState)result.AsyncState;

            try
            {
                var recordsAffected = state.Command.EndExecuteNonQuery(result);
                EventLoop.Pend(() => state.Callback(null, recordsAffected));
            } catch (Exception ex)
            {
                EventLoop.Pend(() => state.Callback(ex, -1));
            }
        }
Example #26
0
        public void InitializeGame()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;

            path += "testmap.txt";
            loop  = new EventLoop();
            game  = new Game(path, true);

            loop.DownHandler  += game.OnDown;
            loop.UpHandler    += game.OnUp;
            loop.LeftHandler  += game.OnLeft;
            loop.RightHandler += game.OnRight;
        }
Example #27
0
        public void Test_ClientRpc()
        {
            string host = "121.36.16.144";
            int    port = 11240;

            EventLoop loop = new EventLoop();

            ClientEnd c = new ClientEnd(loop, host, port);

            c.Connect();

            loop.Run();
        }
Example #28
0
 protected void Dispose(bool disposing)
 {
     if (!WasDisposed)
     {
         WasDisposed = true;
         if (disposing)
         {
             Close();
             Socket = null;
             EventLoop.Dispose();
         }
     }
 }
Example #29
0
 // Runs an action within the session. Safe to call from any thread.
 private void RunInSession(Action action)
 {
     // The action will be run by the library within EventLoop.Run(),
     // so there will always be a running session when the action runs.
     EventLoop.RunOnLoop(() =>
     {
         // If the session is no longer running, ignore the action.
         if (RunningSession == this)
         {
             action.Invoke();
         }
     });
 }
Example #30
0
        public override void Close(Exception reason)
        {
            InvokeDisconnectIfNotNull(RemoteHost, new HeliosConnectionException(ExceptionType.Closed, reason));

            if (_client == null || WasDisposed || !IsOpen())
            {
                return;
            }

            _client.Close();
            EventLoop.Shutdown(TimeSpan.FromSeconds(2));
            _client = null;
        }
Example #31
0
        private void DoWork(object workItemState)
        {
            var aleContext = new AleContext(_context);

            EventLoop.Pend(() =>
            {
                Server.Create().Execute(aleContext);
                if (_callback != null)
                {
                    _callback(this);
                }
            });
        }
Example #32
0
        private void AcceptCallback(IAsyncResult ar)
        {
            var newSocket = Listener.EndAccept(ar);
            var node      = NodeBuilder.FromEndpoint((IPEndPoint)newSocket.RemoteEndPoint);

            var receiveState    = CreateNetworkState(newSocket, node);
            var responseChannel = new TcpReactorResponseChannel(this, newSocket, EventLoop.Clone(ProxiesShareFiber));

            SocketMap.Add(node, responseChannel);
            NodeConnected(node, responseChannel);
            newSocket.BeginReceive(receiveState.RawBuffer, 0, receiveState.RawBuffer.Length, SocketFlags.None, ReceiveCallback, receiveState);
            Listener.BeginAccept(AcceptCallback, null); //accept more connections
        }
Example #33
0
 private static void FileReadAllAsync(string path, Action <Exception, byte[]> complete)
 {
     try
     {
         var fs     = System.IO.File.OpenRead(path);
         var buffer = new byte[fs.Length];
         var state  = new AsyncFileReadState(complete, fs, buffer);
         fs.BeginRead(buffer, 0, buffer.Length, FileReadAllCallback, state);
     } catch (Exception ex)
     {
         EventLoop.Pend(() => complete(ex, null));
     }
 }
Example #34
0
            private void OnEndReceive(IAsyncResult result)
            {
                last_recv_time = DateTime.Now;
                try
                {
                    Socket socket        = (Socket)result.AsyncState;
                    Int32  recvBytesSize = socket.EndReceive(result);
                    if (0 == recvBytesSize)
                    {
                        EventLoop.EnqueuEvent(new CloseEvent(session));
                        return;
                    }
                    receiveBuffer.Append(this.receiveBytes, 0, recvBytesSize);
                }
                catch (ObjectDisposedException e)
                {
                    Debug.Log(e.Message);
                    //EventLoop.EnqueuEvent(new CloseEvent(session));
                    return;
                }
                catch (SocketException e)
                {
                    Debug.Log(e.Message);
                    EventLoop.EnqueuEvent(new CloseEvent(session));
                    return;
                }

                while (Packet.HEADER_SIZE <= receiveBuffer.Size())
                {
                    Packet packet = new Packet(receiveBuffer);
                    if (packet.Length > Gamnet.Buffer.MAX_BUFFER_SIZE)
                    {
                        EventLoop.EnqueuEvent(new CloseEvent(session));
                        return;
                    }

                    if (packet.Length > receiveBuffer.Size())
                    {
                        // not enough
                        BeginReceive();
                        return;
                    }

                    receiveBuffer.Remove(packet.Length);
                    receiveBuffer = new Buffer(receiveBuffer);

                    EventLoop.EnqueuEvent(new ReceiveEvent(session, packet));
                }

                BeginReceive();
            }
Example #35
0
 public void Stop()
 {
     CheckWasDisposed();
     try
     {
         Listener.Shutdown(SocketShutdown.Both);
         EventLoop.Shutdown(TimeSpan.FromSeconds(2));
     }
     catch
     {
     }
     IsActive = false;
     StopInternal();
 }
Example #36
0
        public static async Task WebServer()
        {
            var listener = new HttpListener();

            listener.Prefixes.Add("http://localhost:3000/");
            listener.Start();

            while (true)
            {
                var context = await listener.GetContextAsync();

                EventLoop.Run(() => WebServerRequest(context));
            }
        }
Example #37
0
        public void StartWithCallback()
        {
            // arrange
            var loop = new EventLoop();
            var wait = new AutoResetEvent(false);

            // act
            loop.Start(() => wait.Set());

            // assert
            Assert.That(() => wait.WaitOne(100), Is.True);

            // cleanup
            loop.Dispose();
            wait.Dispose();
        }
        public override void UponReceiptBy(EventLoop eventLoop, string senderAddress)
        {
            // "serviceIdentifiers" contains a list of TypeTags which are identifying for each service
            // Since one TypeTag can have many services attached (which identify themselves with the same TypeTag),
            // "services" contains this list of services.
            // Since a service can be anything (RemoteReference, String, int, etc) we must also keep the type,
            // This type is kept in "serviceTypes";

            // What we need to do is loop over every <list of services> (outer for loop)
            // Then you loop over every service in the <list of services> (inner for loop)
            // This calls the "OnServiceDiscovered" event with the appropriate service identifier (the TypeTag)
            // But you also need to convert the service to the correct type, since the type information is sometimes lost in serialization

            for (int i = 0; i < services.Count; i++)
                for (int j = 0; j < services[i].Count; j++)
                    eventLoop.discoveryManager.serviceManager.importedServiceManager.AddService(typetags[i], serviceIdentifiers[i][j], senderAddress, this.ConvertToType(services[i][j], serviceTypes[i][j]));
        }
Example #39
0
        public void StartWithCallbackCalledTwice()
        {
            // arrange
            var loop = new EventLoop();
            var wait = new CountdownEvent(2);

            // act
            loop.Start(() => wait.Signal());
            loop.Start(() => wait.Signal());

            // assert
            Assert.That(() => wait.WaitHandle.WaitOne(100), Is.True);
            Assert.That(wait.CurrentCount, Is.EqualTo(0));

            // cleanup
            loop.Dispose();
            wait.Dispose();
        }
Example #40
0
        public void Schedule()
        {
            // arrange
            var loop = new EventLoop();
            var wait = new AutoResetEvent(false);
            var counter = 0;

            // act
            loop.Schedule(() => counter++);
            loop.Schedule(() => counter++);
            loop.Start(() => wait.Set());
            loop.Schedule(() => counter++);

            // assert
            Assert.That(() => wait.WaitOne(100), Is.True);
            Assert.That(counter, Is.EqualTo(3));

            // cleanup
            loop.Dispose();
            wait.Dispose();
        }
Example #41
0
        public static void Main(string[] args)
        {
            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();

            IPHostEntry ipHostInfo = Dns.Resolve (Dns.GetHostName ());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
            try{
                listeners += new EventLoop(nextMessage);
                client = new SocketClientExample (remoteEP);
                client.connect();
                client.listeners += new MessageListener(recievedMessage);
                Console.WriteLine("Listener Length: {0}", listeners.GetInvocationList().Length.ToString());
                while (listeners.GetInvocationList().Length > 0){
                    listeners();
                }
                Console.WriteLine("Finished Exec");
            }catch(Exception e){
                Console.WriteLine (e.ToString());
            }
        }
Example #42
0
 public void TestLoopEvent()
 {
   var ea = new EventSink<int>();
   Event<int> ec = Transaction.Run(() =>
   {
     var eb = new EventLoop<int>();
     Event<int> ec_ = Event<int>.MergeWith<int>((x, y) => x + y, ea.Map<int>(x => x % 10), eb);
     Event<int> ebOut = ea.Map<int>(x => x / 10).Filter(x => x != 0);
     eb.Loop(ebOut);
     return ec_;
   });
   var @out = new List<int>();
   Listener l = ec.Listen(x => { @out.Add(x); });
   ea.Send(2);
   ea.Send(52);
   l.Unlisten();
   CollectionAssert.AreEqual(new[] { 2, 7 }, @out.ToArray());
 }
 public override void UponReceiptBy(EventLoop eventLoop, string senderAddress)
 {
     eventLoop.discoveryManager.OnNetworkRequireServicesReceived(serviceSubscriptions, senderAddress);
 }
Example #44
0
        public void TrackResourceCancel()
        {
            // arrange
            var cts = new CancellationTokenSource();
            var token = cts.Token;
            var loop = new EventLoop();
            var cancelled = false;
            token.Register(() => { cancelled = true; });
            loop.TrackResource(token, new DisposeAction(() => { }));

            // act
            cts.Cancel();

            // assert
            Assert.That(cancelled, Is.True);

            // cleanup
            loop.Dispose();
            cts.Dispose();
        }
Example #45
0
        public void TrackResourceDispose()
        {
            // arrange
            var cts = new CancellationTokenSource();
            var token = cts.Token;
            var loop = new EventLoop();
            var disposed = false;
            loop.TrackResource(token, new DisposeAction(() => { disposed = true; }));

            // act
            loop.Dispose();

            // assert
            Assert.That(disposed, Is.True);

            // cleanup
            loop.Dispose();
            cts.Dispose();
        }
Example #46
0
        public void TrackResourceUntrack()
        {
            // arrange
            var cts = new CancellationTokenSource();
            var token = cts.Token;
            var loop = new EventLoop();
            var disposed = false;
            var disposer = new DisposeAction(() => { disposed = true; });
            var untrack = loop.TrackResource(token, disposer);

            // assert
            Assert.That(untrack(token), Is.True, "Expected the resource to be untracked");
            Assert.That(untrack(token), Is.False, "Expected the resource to be untracked already");

            // dispose the loop
            loop.Dispose();
            Assert.That(disposed, Is.False);

            // cleanup
            loop.Dispose();
            cts.Dispose();
        }
Example #47
0
        public void ThrowIfDisposed()
        {
            // arrange
            var loop = new EventLoop();

            // act
            loop.Start(() => { });
            loop.Dispose();

            // assert
            Assert.That(() => loop.Start(() => { }), Throws.InstanceOf<ObjectDisposedException>());
        }
 public override void UponReceiptBy(EventLoop eventLoop, string senderAddress)
 {
     eventLoop.discoveryManager.serviceManager.importedServiceManager.RemoveService(serviceIdentifier);
 }
 public override void UponReceiptBy(EventLoop eventLoop, string senderAddress)
 {
     eventLoop.discoveryManager.serviceManager.importedServiceManager.AddService(typetag, serviceIdentifier, senderAddress, service);
 }
 public override void UponReceiptBy(EventLoop eventLoop, string senderAddress)
 {
     if(valueType != null)
         value = this.ConvertToType(value, valueType);
     eventLoop.discoveryManager.OnNetworkMethodReturnValueReceived(futureReference, value);
 }