Run() 공개 정적인 메소드

public static Run ( ) : void
리턴 void
예제 #1
0
        public void EventLoopRuns()
        {
            var i = 0;

            EventLoop.Run(() => { i++; });
            Assert.Equal(1, i);
        }
예제 #2
0
        public void EventLoopWhenAnyAndAllWorks()
        {
            var threads = new List <int>();
            var i       = 0;

            Task[] tasks  = null;
            Task   finish = null;

            EventLoop.Run(async() =>
            {
                threads.Add(Thread.CurrentThread.ManagedThreadId);
                var first      = new TaskCompletionSource <bool>();
                var second     = new TaskCompletionSource <bool>();
                tasks          = new[] { RecordThreads(threads, first.Task), RecordThreads(threads, second.Task) };
                var finishTask = Task.WhenAny(tasks);
                second.TrySetResult(true);
                first.TrySetResult(true);
                finish = await finishTask;
                await Task.WhenAll(tasks);
                i++;
            });
            Assert.Equal(1, i);
            Assert.Equal(finish, tasks[1]);
            Assert.Equal(5, threads.Count);
            Assert.Equal(1, threads.Distinct().Count());
        }
예제 #3
0
        private static Task Run(IComponentContext c)
        {
            #region DI_Load
            var broker        = c.Resolve <EventBroker>();
            var begin         = DateTimeOffset.Parse("2019-01-01");
            var timeScheduler = new ModelTimeScheduler(ModelTimeStep.Day, begin);

            var manager = c.Resolve <Manager>(new NamedParameter("timeScheduler", timeScheduler));
            var dev1    = c.Resolve <Developer>(
                new NamedParameter("timeScheduler", timeScheduler),
                new NamedParameter("name", "Борис"));
            var dev2 = c.Resolve <Developer>(
                new NamedParameter("timeScheduler", timeScheduler),
                new NamedParameter("name", "Дмитрий"));
            var dev3 = c.Resolve <Developer>(
                new NamedParameter("timeScheduler", timeScheduler),
                new NamedParameter("name", "Илья"));
            #endregion

            var loop = new EventLoop(timeScheduler, broker);

            var a = ModelTimeSpan.FromModelTimeUnits(3);

            timeScheduler.Schedule(ModelTimeSpan.FromModelTimeUnits(3), () =>
            {
                Console.WriteLine("Случается на 3 шаге модельного времени");
            });
            return(loop.Run(time =>
            {
                time.OnUniformTestPassed(t =>
                {
                    manager.GiveNewTaskToTeam("'Важная задача'");
                }, density: 0.5);
            }, 15));
        }
예제 #4
0
 static void Main(string[] args)
 {
     WinEventDelegate dele = new WinEventDelegate(WinEventProc);
     IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
     EventLoop.Run();
   //  Console.ReadKey();
 }
예제 #5
0
파일: Program.cs 프로젝트: tiwb/AngeIO
        static void Main(string[] args)
        {
            // create Event loop
            var loop = new EventLoop();

            // create http server
            var httpsvr = new HttpServer(loop);

            httpsvr.Listen(8080);
            httpsvr.OnRequest += OnHttpRequest;
            httpsvr.OnUpgrade += OnHttpUpgrade;

            // create websocket server
            var wssvr = new WebSocketServer(loop);

            wssvr.OnConnection += OnWebsocketConnected;
            httpsvr.OnUpgrade  += wssvr.HandleUpgrade;

            // create fastcgi server
            var cgisvr = new FastCGIServer(loop);

            cgisvr.OnRequest += OnFastCGIRequest;
            cgisvr.Listen(19000);

            // Run event loop
            loop.Run();
        }
예제 #6
0
        public void UseContextWorks()
        {
            var defaultTaskScheduler = TaskScheduler.Default;
            var v  = 0;
            var ts = new ThreadLocal <int>(() => v++);

            EventLoop.Run(() =>
            {
                var sc   = SynchronizationContext.Current;
                var done = false;

                var threadId     = -1;
                var realThreadId = -1;
                var disp         = DisposableEx.Action(() => threadId = ts.Value).UseContext(sc);
                Task.Factory.StartNew(() =>
                {
                    realThreadId = ts.Value;
                    disp.Dispose();
                    done = true;
                }, CancellationToken.None, TaskCreationOptions.None, defaultTaskScheduler);

                while (!done)
                {
                    EventLoop.DoEvents();
                }
                Assert.Equal(ts.Value, threadId);
                Assert.NotEqual(realThreadId, threadId);
            });
        }
예제 #7
0
        public void EventLoopPassesArg()
        {
            var    test     = new object();
            object received = null;

            EventLoop.Run(x => { received = x; }, test);
            Assert.Equal(test, received);
        }
예제 #8
0
 public static void Main()
 {
     EventLoop.Pump(() =>
     {
         EventLoop.Run(() => Print("http://www.bing.com/"));
         EventLoop.Run(() => Print("http://www.google.com/"));
     });
 }
예제 #9
0
 public static void Main()
 {
     EventLoop.Pump(() =>
     {
         Console.WriteLine("Running on http://localhost:3000/");
         EventLoop.Run(WebServer);
     });
 }
예제 #10
0
        public void EventLoopRecursive()
        {
            var res = 0;

            EventLoop.Run(async() =>
            {
                res = await Recursive(800);
            });
            Assert.Equal(800, res);
        }
예제 #11
0
        static void Main(string[] args)
        {
            var eventLoop = new EventLoop();

            eventLoop.LeftHandler  += Game.OnLeft;
            eventLoop.RightHandler += Game.OnRight;
            eventLoop.UpHandler    += Game.OnUp;
            eventLoop.DownHandler  += Game.OnDown;
            eventLoop.Run();
        }
예제 #12
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();
 }
예제 #13
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();
 }
예제 #14
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);
     }
 }
예제 #15
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();
            }
        }
        private static void Test(Action <SynchronizationContext> action)
        {
            var done = false;

            EventLoop.Run(() =>
            {
                action(SynchronizationContext.Current);
                done = true;
            });
            Assert.True(done);
        }
예제 #17
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();
        }
예제 #18
0
        public void EventLoopRunsAsync()
        {
            var i = 0;

            EventLoop.Run(async() =>
            {
                await Task.Yield();
                i++;
            });
            Assert.Equal(1, i);
        }
예제 #19
0
        public void EventLoopUnhandledPostExceptionWorks()
        {
            var gotIt = false;

            EventLoop.Run(async() =>
            {
                EventLoop.UnhandledException += ex => { gotIt = true; };
                await Throw(1);
            });
            Assert.True(gotIt);
        }
예제 #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();
        }
예제 #21
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();
        }
예제 #22
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();
        }
예제 #23
0
        /// <summary>
        /// Main method of the program
        /// </summary>
        private static void Main(string[] args)
        {
            var eventLoop = new EventLoop();
            var game      = new Game("map.txt");

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

            eventLoop.Run();
        }
예제 #24
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));
            }
        }
예제 #25
0
파일: Program.cs 프로젝트: mihaly044/mstat
        static void Main()
        {
            var window = WinHook.CreateForegroundChangedEventArg().ProcessName;

            WinHook.ForegroundWindowChanged += (sender, arg) => { window = arg.ProcessName; };

            WinHook.MouseChanged += (sender, arg) =>
            {
                var click = arg.Msg == 513 ? "WM_LBUTTONDOWN" : "WM_LBUTTONUP";
                Console.WriteLine($"{window} {click} @ ({arg.X},{arg.Y})");
            };

            EventLoop.Run();
        }
예제 #26
0
        static void Main(string[] args)
        {
            var eventLoop = new EventLoop();
            var game      = new Game(FileReader.MakeList("Map.txt"));

            game.Draw(game, null);
            eventLoop.LeftHandler   += game.OnLeft;
            eventLoop.RightHandler  += game.OnRight;
            eventLoop.TopHandler    += game.OnUp;
            eventLoop.BottomHandler += game.OnDown;
            eventLoop.LeftHandler   += game.Draw;
            eventLoop.RightHandler  += game.Draw;
            eventLoop.TopHandler    += game.Draw;
            eventLoop.BottomHandler += game.Draw;
            eventLoop.Run();
        }
예제 #27
0
        static void Main(string[] args)
        {
            var server = new Net.Server(conn =>
            {
                Console.WriteLine("Connection accepted from {0}",
                                  conn.RemoteAddress.ToString());

                conn.OnClose += wasError =>
                {
                    Console.WriteLine("Connection from {0} was closed",
                                      conn.RemoteAddress.ToString());
                };

                conn.OnData += data =>
                {
                    byte[] response = Encoding.ASCII.GetBytes(
                        "HTTP/1.0 200 OK\r\n" +
                        "Content-Type:text/plain\r\n" +
                        "Content-Length:" + data.Length + "\r\n" +
                        "\r\n");

                    int len = response.Length;

                    Array.Resize(ref response,
                                 response.Length + data.Length);

                    //Array.Copy(data, 0, response, len, data.Length);

                    for (int i = 0; i < data.Length; i++)
                    {
                        response[i + len] = data[i];
                    }

                    conn.Write(response, () =>
                    {
                        conn.End();
                    });
                };
            }).Listen(8080, listeningListener: () =>
            {
                Console.WriteLine("Listening on port 8080");
            });

            EventLoop.Run();
        }
예제 #28
0
        public void EventLoopCancellationWorks()
        {
            var i       = 0;
            var threads = new List <int>();

            EventLoop.Run(() =>
            {
                threads.Add(Thread.CurrentThread.ManagedThreadId);
                var tcs  = new TaskCompletionSource <bool>();
                var task = RecordThreads(threads, tcs.Task);
                tcs.TrySetCanceled();
                Assert.True(task.IsCanceled);
                i++;
            });
            Assert.Equal(1, i);
            Assert.Equal(2, threads.Count);
            Assert.Equal(1, threads.Distinct().Count());
        }
예제 #29
0
        //[Fact]
        public void DisposingLetNoEventsBeDispatched()
        {
            var brokerMock    = new Mock <IObservable <IRxModellingEvent> >();
            var timeScheduler = new ModelTimeScheduler(ModelTimeStep.Day, DateTimeOffset.Parse("2019-01-01"));

            var loop = new EventLoop(timeScheduler, brokerMock.Object);

            loop.Run(time =>
            {
                time.OnUniformTestPassed(t =>
                {
                }, 0.2);
            }, 15);

            Thread.Sleep(80);

            loop.Dispose();
            Console.WriteLine("loop disposed");
            Thread.Sleep(TimeSpan.FromSeconds(10));
        }
예제 #30
0
        public void EventLoopRunsOnSameThread()
        {
            var threads = new List <int>();
            var i       = 0;

            EventLoop.Run(async() =>
            {
                threads.Add(Thread.CurrentThread.ManagedThreadId);
                var tcs = new TaskCompletionSource <bool>();
                var rt1 = RecordThreads(threads, tcs.Task);
                var rt2 = RecordThreads(threads, tcs.Task);
                tcs.TrySetResult(true);
                await rt1;
                await rt2;
                i++;
            });
            Assert.Equal(1, i);
            Assert.Equal(5, threads.Count);
            Assert.Equal(1, threads.Distinct().Count());
        }
예제 #31
0
        public void EventLoopPostAwaitExceptionWorks()
        {
            var i     = 0;
            var gotIt = false;

            EventLoop.Run(async() =>
            {
                try
                {
                    await Throw(1);
                }
                catch (InvalidOperationException)
                {
                    gotIt = true;
                }
                i++;
            });
            Assert.Equal(1, i);
            Assert.True(gotIt);
        }
예제 #32
0
        public async Task UniformTestProvidesFairEventDensity(double eventStreamDensity)
        {
            var brokerMock     = new Mock <IObservable <IRxModellingEvent> >();
            var timeScheduler  = new ModelTimeScheduler(ModelTimeStep.Day, DateTimeOffset.Parse("2019-01-01"));
            var triggeredTimes = 0;

            var loop = new EventLoop(timeScheduler, brokerMock.Object);
            await loop.Run(time =>
            {
                time.OnUniformTestPassed(t =>
                {
                    triggeredTimes++;
                }, eventStreamDensity);
            }, LongSimulationTimeInTicks);

            var actualDensity = (double)triggeredTimes / LongSimulationTimeInTicks;

            _output.WriteLine($"exp: {eventStreamDensity} vs act: {actualDensity}");
            AssertPlus.EqualFloats(
                expected: eventStreamDensity,
                actual: (double)triggeredTimes / LongSimulationTimeInTicks
                );
        }