Esempio n. 1
0
        static void Main(string[] _)
        {
            var size = Marshal.SizeOf(typeof(D3D11_INPUT_ELEMENT_DESC));

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var window = Window.Create();

            if (window == null)
            {
                throw new Exception("fail to create window");
            }

            using (var d3d = new D3DApp())
            {
                window.OnResize += (w, h) =>
                {
                    d3d.Resize(window.WindowHandle, w, h);
                };

                MessageLoop.Run(() =>
                {
                    d3d.Draw(window.WindowHandle);
                }, 30);
            }
        }
Esempio n. 2
0
        public void Test()
        {
            using (var loop = new MessageLoop<MsgLoopTests>(this))
                Parallel.For(0, Iters, i => loop.Do(x => ++x._i));

            Assert.AreEqual(Iters, _i);
        }
Esempio n. 3
0
        public void CanInterceptNestedMessages() => AsyncContext.Run(async() =>
        {
            var normalInterceptions = 0;
            var nestedInterceptions = 0;

            const int expected = 123;
            using (var loop = new MessageLoop <int>(() => expected, interceptor: (i, ctx) =>
            {
                if (ctx.NestedMessage)
                {
                    nestedInterceptions++;
                }
                else
                {
                    normalInterceptions++;
                }

                return(ctx.Func(i));
            }))
            {
                var x = await loop.GetAsync(async n => await loop.GetAsync(async n2 => await loop.GetAsync(n3 => n3)));
                Assert.AreEqual(expected, x);
                Assert.AreEqual(1, normalInterceptions);
                Assert.AreEqual(2, nestedInterceptions);
            }
        });
Esempio n. 4
0
        public void CanInterceptMessages() => AsyncContext.Run(async() =>
        {
            var i = 0;

            using (var loop = new MessageLoop <int>(() => 0, interceptor: async(s, ctx) =>
            {
                i++;
                try
                {
                    var result = await ctx.Func(s);
                    return(result);
                }
                finally
                {
                    i++;
                }
            }))
            {
                await loop.DoAsync(w => Task.FromResult(i++));
                try
                {
                    await loop.DoAsync(w => DivZero());
                }
                catch
                {
                }
            }

            Assert.AreEqual(5, i);
        });
Esempio n. 5
0
        public void Test()
        {
            using (var loop = new MessageLoop <MsgLoopTests>(this))
                Parallel.For(0, Iters, i => loop.Do(x => ++ x._i));

            Assert.AreEqual(Iters, _i);
        }
Esempio n. 6
0
        private void MessageLoopButton_OnClick(object sender, RoutedEventArgs e)
        {
            MessageLoop win = new MessageLoop();

            _messageLoopWin = win;
            win.Show();
        }
Esempio n. 7
0
        public void TestMessageLoop()
        {
            /* GIVEN */
            var autoResetEvent = new AutoResetEvent(false);
            var messageLoop    = new MessageLoop();

            /* WHEN */
            var cancelThread = new Thread(() =>
            {
                while (!messageLoop.IsRunning)
                {
                    /*
                     * We need to wait until it actually started.
                     * However this will stop if the autoResetEvent is not fulfilled in time.
                     */
                }

                autoResetEvent.Set();
                messageLoop.Stop();
            });

            cancelThread.Start();
            messageLoop.Start();

            /* THEN */
            Assert.IsTrue(autoResetEvent.WaitOne(waitTimeInMilliseconds));
        }
Esempio n. 8
0
            public async Task ProcessMessages([Frozen] IMessageService messageService, [Frozen] BaseRequest message,
                                              MessageLoop sut)
            {
                await sut.Start();

                messageService.Received(1).Process(message, Arg.Any <Stream>(), Arg.Any <Stream>());
            }
Esempio n. 9
0
        public void Stress() => AsyncContext.Run(async() =>
        {
            const int workerCount = 10;
            const int iters       = 100;

            using (var loop = new MessageLoop <Wrapper <int> >(() => new Wrapper <int>()))
            {
                var workers = System.Linq.Enumerable.Range(0, workerCount)
                              .Select(i =>
                {
                    return(Task.Run(() =>
                    {
                        for (int j = 0; j < iters; j++)
                        {
                            loop.DoAsync(w => w.Value++).Wait();
                        }
                    }));
                }).ToArray();

                Task.WaitAll(workers);

                var n = await loop.GetAsync(async x =>
                {
                    return(await Task.FromResult(x.Value));
                });
                Assert.AreEqual(workerCount * iters, n);
            }
        });
Esempio n. 10
0
 private void Exit(object sender, EventArgs eventArgs)
 {
     Overlay.Overlay.Instance.Stop();
     MessageLoop.GetInstance().Stop();
     _trayIcon.Visible = false;
     Application.Exit();
 }
Esempio n. 11
0
        public void Stress() => AsyncContext.Run(async () =>
        {
            const int workerCount = 10;
            const int iters = 100;

            using (var loop = new MessageLoop<Wrapper<int>>(() => new Wrapper<int>()))
            {
                var workers = System.Linq.Enumerable.Range(0, workerCount)
                .Select(i =>
                {
                    return Task.Run(() =>
                    {
                        for (int j = 0; j < iters; j++)
                        {
                            loop.DoAsync(w => w.Value++).Wait();
                        }
                    });
                }).ToArray();

                Task.WaitAll(workers);

                var n = await loop.GetAsync(async x =>
                {
                    return await Task.FromResult(x.Value);
                });
                Assert.AreEqual(workerCount*iters, n);
            }
        });
Esempio n. 12
0
 static void Main(string[] args)
 {
     MessageLoop.EnsureContext();
     using (var man = new Manager())
     {
         man.Run();
     }
 }
Esempio n. 13
0
 public void CanGetAsync() => AsyncContext.Run(async() =>
 {
     using (var loop = new MessageLoop <int>(() => 1))
     {
         var n = await loop.GetAsync(x => x);
         Assert.AreEqual(1, n);
     }
 });
Esempio n. 14
0
 public void CanGetAsync() => AsyncContext.Run(async () =>
 {
     using (var loop = new MessageLoop<int>(() => 1))
     {
         var n = await loop.GetAsync(x => x);
         Assert.AreEqual(1, n);
     }
 });
Esempio n. 15
0
 public void Send(DhtMessage msg, IPEndPoint endpoint)
 {
     if (msg is FindNodeResponse && MessageLoop.GetWaitSendCount() > MaxSendQueue)
     {
         return;
     }
     MessageLoop.EnqueueSend(msg, endpoint);
 }
Esempio n. 16
0
        private static void Main(string[] args)
        {
            var key = new KeyCombinationHandler(VirtualKeyCode.KeyA);

            using (KeyboardHook.KeyboardEvents.Where(key).Subscribe(e => Hit()))
            {
                MessageLoop.ProcessMessages();
            }
        }
Esempio n. 17
0
 public void CanDoAsync() => AsyncContext.Run(async() =>
 {
     using (var loop = new MessageLoop <int>(() => 1))
     {
         int n = 0;
         await loop.DoAsync(x => n = x);
         Assert.AreEqual(1, n);
     }
 });
Esempio n. 18
0
 public void CanDoAsync() => AsyncContext.Run(async () =>
 {
     using (var loop = new MessageLoop<int>(() => 1))
     {
         int n = 0;
         await loop.DoAsync(x => n = x);
         Assert.AreEqual(1, n);
     }
 });
Esempio n. 19
0
        private static RequestDelegate NewEventService(Events e)
        {
            return(async(server, request, response) => {
                var pid = uint.Parse(request.Body);
                var hook = await MessageLoop.AddHook(e, pid).Task;

                await response.WriteText(hook.ToString());
            });
        }
Esempio n. 20
0
 public void Start(Node[] initialNodes)
 {
     MessageLoop.Start();
     foreach (var item in initialNodes)
     {
         SendFindNode(item);
     }
     RaiseStateChanged(DhtState.Ready);
 }
Esempio n. 21
0
 public void CanNestMessages() => AsyncContext.Run(async() =>
 {
     const int expected = 123;
     using (var loop = new MessageLoop <int>(() => expected))
     {
         var x = await loop.GetAsync(async n => await loop.GetAsync(async n2 => await loop.GetAsync(n3 => n3)));
         Assert.AreEqual(expected, x);
     }
 });
Esempio n. 22
0
 public void StartListening()
 {
     if (IsListening)
     {
         return;
     }
     _messageLoop = new MessageLoop(_netServer, _messageRouter.Route);
     _netServer.Start();
 }
Esempio n. 23
0
        static void Main(string[] args)
        {
            using (var app = new App())
            {
                app.Bind(Window.Create(), BuildUI());

                MessageLoop.Run(app.Draw, 30);
            }
        }
Esempio n. 24
0
        public void Dispose()
        {
            _netServer.Shutdown("Endpoint disposed");
            _netServer.WaitForClose();

            if (_messageLoop != null)
            {
                _messageLoop.Dispose();
            }
            _messageLoop = null;
        }
Esempio n. 25
0
 public virtual void Open()
 {
     if (IsOpen)
     {
         throw new InvalidOperationException("Channel already opened.");
     }
     _messageLoop = new MessageLoop(Client, MessageRouter.Route);
     Client.Start();
     Connection = Client.Connect(Host, Port);
     Connection.WaitForConnectionToOpen();
 }
Esempio n. 26
0
        public DhtSpider(DhtListener listener)
        {
            if (listener == null)
            {
                throw new ArgumentNullException("listener");
            }

            TokenManager = new EasyTokenManager();
            LocalId      = NodeId.Create();
            MessageLoop  = new MessageLoop(this, listener);
            MessageLoop.ReceivedMessage += MessageLoop_ReceivedMessage;
        }
Esempio n. 27
0
        public WebSocket(IntPtr handle) : base(handle)
        {
            HandleMessage += OnReceiveMessage;

            // Create and start the general message loop
            messageLoop = new MessageLoop(this);
            messageLoop.Start();

            // Create and start the receive message loop
            receiveLoop = new MessageLoop(this);
            receiveLoop.Start();
        }
Esempio n. 28
0
        public static void Main()
        {
            Overlay.Overlay.Instance.Run();
            MessageLoop.GetInstance().Run();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new TrayForm());

            Overlay.Overlay.Instance.Join();
            MessageLoop.GetInstance().Join();

            HotkeyProcessor.GetInstance().Close();
        }
Esempio n. 29
0
        public void SendFindNodes()
        {
            var waitsend = MessageLoop.GetWaitSendCount();

            lock (NextNodes)
            {
                for (int i = 0; i < NextNodes.Count && waitsend < MaxFindSendPer; i++)
                {
                    var next = NextNodes.Dequeue();
                    SendFindNode(next);
                    waitsend++;
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Closes channel.
        /// It should not throw if channel is already closed.
        /// </summary>
        public override void Close()
        {
            base.Close();
            if (Client.Status == NetPeerStatus.Running || Client.Status == NetPeerStatus.Starting)
            {
                Client.Shutdown("Client disposed");
                Client.WaitForClose();
            }

            if (MessageLoop != null)
            {
                MessageLoop.Dispose();
            }
            _messageLoop = null;
        }
Esempio n. 31
0
        private void OnInitialize(object sender, InitializeEventArgs args)
        {
            // Open the file system on the file_thread_. Since this is the first
            // operation we perform there, and because we do everything on the
            // file_thread_ synchronously, this ensures that the FileSystem is open
            // before any FileIO operations execute.
            messageLoop = new MessageLoop(this);
            var startTask = messageLoop.Start();

            runloop = new MessageLoop(this);
            runloop.Start();

            // Set the MessageLoop that the filesystem will run asynchronously with
            // This is not necassary though as the async will run regardless if a
            // MessageLoop is set or not.
            fileSystem.MessageLoop = messageLoop;

            OpenFileSystem();
        }
Esempio n. 32
0
        public async Task Start()
        {
            bodyMessageLoop = new MessageLoop(instance);
            bodyMessageLoop.Start();

            var openresult = await urlLoader.OpenAsync(urlRequest, bodyMessageLoop);

            if (openresult != PPError.Ok)
            {
                ReportResultAndDie(url, "URLLoader.Open() failed", false);
                return;
            }
            // Here you would process the headers. A real program would want to at least
            // check the HTTP code and potentially cancel the request.
            // var response = loader.ResponseInfo;
            var response = urlLoader.ResponseInfo;

            instance.LogToConsole(PPLogLevel.Warning, response.ToString());

            // Try to figure out how many bytes of data are going to be downloaded in
            // order to allocate memory for the response body in advance (this will
            // reduce heap traffic and also the amount of memory allocated).
            // It is not a problem if this fails, it just means that the
            // urlResponseBody.Append call in URLLoaderHandler:AppendDataBytes()
            // will allocate the memory later on.
            long bytesReceived          = 0;
            long totalBytesToBeReceived = 0;

            if (urlLoader.GetDownloadProgress(out bytesReceived, out totalBytesToBeReceived))
            {
                if (totalBytesToBeReceived > 0)
                {
                    urlResponseBody = new StringBuilder((int)totalBytesToBeReceived);
                }
            }

            // We will not use the download progress anymore, so just disable it.
            urlRequest.SetRecordDownloadProgress(false);
            // Start streaming.
            await ReadBody();
        }
Esempio n. 33
0
        static void Main(string[] args)
        {
            var window = Window.Create();

            if (window == null)
            {
                throw new Exception("fail to create window");
            }

            using (var d3d = new D3DApp())
            {
                window.OnResize += (w, h) =>
                {
                    d3d.Resize(window.WindowHandle, w, h);
                };

                MessageLoop.Run(() =>
                {
                    d3d.Draw(window.WindowHandle);
                }, 30);
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Starts this Window. (shows and begins event handling)
        /// </summary>
        public void Start()
        {
            if(Started)
            {
                throw new Exception("Window already started!");
            }

            //specify the creation parameters
            CreateParams paras = new CreateParams();
            paras.Caption = "";
            paras.ClassStyle = 0x0003;//CS_HREDRAW | CS_VREDRAW
            paras.Style = DEFAULT_WINDOW_STYLE;
            Rectangle dimension = GetWindowDimensions();
            paras.X = dimension.X;
            paras.Y = dimension.Y;
            paras.Width = dimension.Width;
            paras.Height = dimension.Height;

            //start message loop
            MessageLoopObj = new MessageLoop();
            MessageLoopObj.Start<object>(() => CreateHandle(paras));

            Started = true;

            //if pending fullscreen, actually perform action
            if(Fullscreen)
                Fullscreen = true;

            ShowWindow(Handle, 1);//WINDOW_SHOW_NORMAL

            //if pending maximize, actually perform action
            if(Maximized)
                Maximized = true;
        }
Esempio n. 35
0
 async Task test()
 {
     using (var loop = new MessageLoop <string>(() => ""))
         await loop.GetAsync(state => Task.FromResult(DivZero()));
 }
Esempio n. 36
0
 public void TestDoException() => AsyncContext.Run(async () =>
 {
     using (var loop = new MessageLoop<string>(() => ""))
         await loop.DoAsync(state => DivZero());
 });
Esempio n. 37
0
 public void CanNestMessages() => AsyncContext.Run(async () =>
 {
     const int expected = 123;
     using (var loop = new MessageLoop<int>(() => expected))
     {
         var x = await loop.GetAsync(async n => await loop.GetAsync(async n2 => await loop.GetAsync(n3 => n3)));
         Assert.AreEqual(expected, x);
     }
 });
Esempio n. 38
0
        public void CanInterceptMessages() => AsyncContext.Run(async () =>
        {
            var i = 0;

            using (var loop = new MessageLoop<int>(() => 0, interceptor: async (s, ctx) =>
            {
                i++;
                try
                {
                    var result = await ctx.Func(s);
                    return result;
                }
                finally
                {
                    i++;
                }
            }))
            {
                await loop.DoAsync(w => Task.FromResult(i++));
                try
                {
                    await loop.DoAsync(w => DivZero());
                }
                catch
                {
                }
            }

            Assert.AreEqual(5, i);
        });
Esempio n. 39
0
        public void CanInterceptNestedMessages() => AsyncContext.Run(async () =>
        {
            var normalInterceptions = 0;
            var nestedInterceptions = 0;

            const int expected = 123;
            using (var loop = new MessageLoop<int>(() => expected, interceptor: (i, ctx) =>
            {
                if (ctx.NestedMessage) nestedInterceptions++;
                else normalInterceptions++;

                return ctx.Func(i);
            }))
            {
                var x = await loop.GetAsync(async n => await loop.GetAsync(async n2 => await loop.GetAsync(n3 => n3)));
                Assert.AreEqual(expected, x);
                Assert.AreEqual(1, normalInterceptions);
                Assert.AreEqual(2, nestedInterceptions);

            }
        });
Esempio n. 40
0
 public void TestGetAsyncException() => AsyncContext.Run(async () => 
 {
     using (var loop = new MessageLoop<string>(() => ""))
         await loop.GetAsync(state => Task.FromResult(DivZero()));
 });