protected override void OnStart(string[] args)
        {
            int          port    = 8001;
            AsyncService service = new AsyncService(port, new CalcHandler());

            service.Run();
        }
Exemple #2
0
        public void CallAsync_wait_done()
        {
            var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();

            var done = new ManualResetEvent(false);
            var srv = new AsyncService(done);
            var callback = new AsyncServiceCallback();

            using (var host = new ServiceHost(srv, new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(IAsyncService), binding, address);
                host.Open();

                ThreadPool.QueueUserWorkItem(_ =>
                    {
                        using (var factory = new DuplexChannelFactory<IAsyncService>(new InstanceContext(callback), binding))
                        {
                            var client = factory.CreateChannel(new EndpointAddress(address));
                            AsyncCallback act = (x) =>
                            {
                                Assert.AreEqual(x.AsyncState, 1);
                            };
                            var result = client.BeginServiceAsyncMethod(act, 1);
                            result.AsyncWaitHandle.WaitOne();
                            Assert.AreEqual(result.AsyncState, 1);
                            client.EndServiceAsyncMethod(result);

                        }
                    });

                done.WaitOne();
            }
        }
Exemple #3
0
        // Returns true if it was successful in returning it to the pool
        public bool AttemptToUnload()
        {
            if (unload)
            {
                if (GetLoadState() == ChunkLoadState.LoadingFromDisk)
                {
                    return(false);
                }

                if (GetLoadState() == ChunkLoadState.BlocksGenerating ||
                    GetLoadState() == ChunkLoadState.MeshCalculating)
                {
                    bool workRevoked = AsyncService.GetCPUMediator().CancelProcessingRequest(this);
                    if (!workRevoked)
                    {
                        return(false);
                    }
                }

                if (GetLoadState() != ChunkLoadState.WaitingToGenerateBlocks)
                {
                    Save();
                }

                GeneratorService.ReturnChunk(this);
                return(true);
            }

            return(false);
        }
Exemple #4
0
        public static void StartService()
        {
            try
            {
                //DeliveryNote d = new DeliveryNote();
                //d.foremanid = 1;
                //d.orderid = 4;
                //d.success = true;
                //DbHandler.addDeliveryNote(d);
                //
                //foreach (Order o in orders) {
                //    Console.WriteLine(o.Terminal);
                //}
                //List<DeliveryNote> notes = DbHandler.GetDeliveryNotes();
                //foreach(DeliveryNote d in notes)
                //{
                //    Console.WriteLine(d.orderid);
                //}

                int port = 50000;
                service = new AsyncService(port);
                service.Run();
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
        private static async Task Main(string[] args)
        {
            WriteCommandLineArguments(args);

            await TimeSpan.FromSeconds(2);

            await Task.Delay(2_000);

            Console.WriteLine("Hello .NET Community Austria!");
            Console.WriteLine();

            await Awaiters.DetachCurrentSyncContext();

            await AsyncService.WriteAsync();

            await WriteNuGetDownloadsAsync();

            var cts = new CancellationTokenSource();

            cts.Cancel();
            try
            {
                await ProcessService.RunAsync("dotnet", "--version", cts.Token);
            }
            catch (TaskCanceledException)
            {
                Console.WriteLine("The operation was canceled.");
            }
        }
Exemple #6
0
        void OnApplicationQuit()
        {
            AsyncService.GetCPUMediator().Shutdown();

            UnityEngine.Debug.Log("Saving all loaded chunks...");
            ChunkRepository.SaveAllLoadedChunks();
            FileRepository.Shutdown();
            UnityEngine.Debug.Log("Done.");
        }
Exemple #7
0
 void OnGUI()
 {
     if (showDebugMenu)
     {
         GUI.Box(uiThreadQueueSizeRect, "Thread queue size: " + AsyncService.ThreadQueueSize().ToString());
         GUI.Box(uiProcessingListSizeRect, "Processing chunk queue size: " + ChunkRepository.GetProcessingChunkListSize().ToString());
         GUI.Box(uiTotalChunkCountRect, "Chunk pool size: " + GeneratorService.TotalChunkCount().ToString());
         GUI.Box(uiUnloadChunkCountRect, "Queued chunk unloads: " + GeneratorService.UnloadChunksListCount().ToString());
     }
 }
Exemple #8
0
 public void Generate(Chunk northChunk, Chunk southChunk,
                      Chunk westChunk, Chunk eastChunk,
                      Chunk aboveChunk, Chunk belowChunk)
 {
     this.northChunk = northChunk;
     this.southChunk = southChunk;
     this.westChunk  = westChunk;
     this.eastChunk  = eastChunk;
     this.aboveChunk = aboveChunk;
     this.belowChunk = belowChunk;
     AsyncService.GetCPUMediator().EnqueueBatchForProcessing(generateMeshWorkFunction, (object)this,
                                                             CPUMediator.HIGH_PRIORITY, transform.position);
 }
Exemple #9
0
 private void Start()
 {
     try
     {
         int          port    = 5000;
         AsyncService service = new AsyncService(port, this);
         service.Run(); // very specific service
     }
     catch (Exception ex)
     {
         Debug.Log(ex.Message);
     }
 }
        public void Execute()
        {
            var ids = Enumerable.Range(StartId, CountIds).ToArray();

            var tasks = ids.Select(id => AsyncService.RunAsync(doc => DoWork(doc, id))).ToArray();

            Task.WaitAll(tasks);

            var changed = Container.Instances <SalesOrderHeader>().Where(soh => ids.Contains(soh.SalesOrderID)).ToArray();

            Assert.AreEqual(CountIds, changed.Length);
            changed.ForEach(soh => Assert.AreEqual(testMessage + soh.SalesOrderID, soh.Comment));
        }
Exemple #11
0
        void Start()
        {
            if (player == null)
            {
                throw new MissingComponentException("Missing Player component");
            }
            if (blockParticle == null)
            {
                throw new MissingComponentException("Missing Block Particle component");
            }
            if (chunkMeshPrefab == null)
            {
                throw new MissingComponentException("Missing Chunk Mesh component");
            }
            if (solidBlockMaterial == null)
            {
                throw new MissingComponentException("Missing Solid Block Material component");
            }
            if (transparentBlockMaterial == null)
            {
                throw new MissingComponentException("Missing Transparent Block Material component");
            }
            if (waterBlockMaterial == null)
            {
                throw new MissingComponentException("Missing Water Block Material component");
            }

            Vector3 playerStartPosition;

            playerStartPosition.x = 64.5f;
            playerStartPosition.y = 148;
            playerStartPosition.z = 64.5f;
            Instantiate(player, playerStartPosition, Quaternion.identity);

            instance = this;
            BlockDefinition.InitializeAllTypes();
            AsyncService.Initialize();
            ChunkRepository.Initialize();
            CollisionService.Initialize();
            GeneratorService.Initialize();
            RenderService.Initialize();

            SetSeed(UnityEngine.Random.Range(Int32.MinValue + 1, Int32.MaxValue - 1));

            fogDistance = 0.0f;

            AsyncService.Load();

            // Remove the next line if you want your game to stop processing when it loses focus
            Application.runInBackground = true;
        }
Exemple #12
0
 static void Main(string[] args)
 {
     try
     {
         AsyncService service = new AsyncService();
         service.Run();
         Console.ReadLine();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         Console.ReadLine();
     }
 }
Exemple #13
0
        public void GenerateBlocks(float seed)
        {
            if (WaitingToGenerateBlocks())
            {
                SetLoadState(ChunkLoadState.BlocksGenerating);

                Vector3 position;
                position.x = worldPosition.x * SIZE;
                position.y = worldPosition.y * SIZE;
                position.z = worldPosition.z * SIZE;
                AsyncService.GetCPUMediator().EnqueueBatchForProcessing(generateBlocksWorkFunction,
                                                                        (object)this, CPUMediator.LOW_PRIORITY, position);
            }
        }
Exemple #14
0
 static void Main(string[] args)
 {
     try
     {
         AsyncService service = new AsyncService();
         service.Run();
         while (true)
         {
             Console.WriteLine("Long Task\n\r");
             Thread.Sleep(1000);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         Console.ReadLine();
     }
 }
Exemple #15
0
        public async System.Threading.Tasks.Task ExternalCallEqualsInternalCall()
        {
            base.Setup();
            var got  = new WeatherData();
            var vm   = new AsyncViewModel(new AsyncService());
            var serv = new AsyncService();

            got = await serv.GetWeatherAsync("84627", "us", WeatherUnits.Metric);

            vm.ZipCode     = "84627";
            vm.CountryCode = "us";

            await vm.Recalculate();

            var expected = vm.Weather.WeatherDayInfo.Temperature;
            var actual   = got.WeatherDayInfo.Temperature;

            Assert.AreEqual(actual, expected);
        }
Exemple #16
0
        public void FlushModifications()
        {
            if (Monitor.TryEnter(padlock))
            {
                if (MeshGenerationIsInProgress() == false)
                {
                    while (modificationList.Count > 0 &&
                           AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_FLUSH_MODIFICATIONS_DEADLINE))
                    {
                        BlockModification modification   = modificationList.Dequeue();
                        BlockDefinition   prevDefinition =
                            blocks[modification.position.x, modification.position.y, modification.position.z].GetDefinition();
                        blocks[modification.position.x, modification.position.y, modification.position.z]
                        .Set(modification.definition);

                        if (modification.definition.IsActive() == false)
                        {
                            FlushBlockRemoval(modification.position, modification.definition, prevDefinition);
                        }
                        else
                        {
                            FlushBlockSet(modification.position, modification.definition, prevDefinition);
                        }
                    }

                    AdjacentTransparencyModification transparencyModification;
                    if (Monitor.TryEnter(adjacentTransparencyModificationList))
                    {
                        while (adjacentTransparencyModificationList.Count > 0 &&
                               AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_FLUSH_MODIFICATIONS_DEADLINE))
                        {
                            transparencyModification = adjacentTransparencyModificationList.Dequeue();
                            SetAdjacentBlockTransparentFlag(transparencyModification.position,
                                                            transparencyModification.xOffset, transparencyModification.yOffset, transparencyModification.zOffset,
                                                            transparencyModification.transparent);
                        }
                        Monitor.Exit(adjacentTransparencyModificationList);
                    }
                }
                Monitor.Exit(padlock);
            }
        }
Exemple #17
0
        public void CallbackAsyncCallback_wait_done()
        {
            var address = @"net.pipe://127.0.0.1/" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name;
            var binding = new NetNamedPipeBinding();

            var srv = new AsyncService(null);
            var callback = new AsyncServiceCallback();

            using (var host = new ServiceHost(srv, new Uri(address)))
            {
                host.AddServiceEndpoint(typeof(IAsyncService), binding, address);
                host.Open();

                using (var factory = new DuplexChannelFactory<IAsyncService>(new InstanceContext(callback), binding))
                {
                    var client = factory.CreateChannel(new EndpointAddress(address));
                    client.DoSyncCall();

                }
            }
        }
Exemple #18
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     Logic.GomEPS    eps = new Logic.GomEPS();
     Logic.IsisTRXVU trx = new Logic.IsisTRXVU();
     trxInit(trx);
     Logic.FRAMLogic fram = new Logic.FRAMLogic();
     try
     {
         AsyncService service = new AsyncService();
         AsyncService.eps  = eps;
         AsyncService.trx  = trx;
         AsyncService.fram = fram;
         Thread newThread = new Thread(AsyncService.Run);
         newThread.Start();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     MainWindow.ChangePanel(new ComponentsTabs(eps, trx));
     // number of trxes.. defaults..
 }
Exemple #19
0
        public async System.Threading.Tasks.Task Test()
        {
            base.Setup();
            var got  = new WeatherData();
            var vm   = new AsyncViewModel(new AsyncService());
            var serv = new AsyncService();


            try
            {
                //Failed Call
                got = await serv.GetWeatherAsync("AFSDFASDF", "us", WeatherUnits.Metric);
            }
            catch (Exception e)
            {
                if (e != null)
                {
                    Assert.Pass();
                }
            }

            Assert.Fail();
        }
 public SearchBingAsyncController()
 {
     _syncService = new AsyncService();
 }
 /// <summary>
 /// Creates the specified service.
 /// </summary>
 /// <param name="service">The service.</param>
 /// <returns></returns>
 public static IConfiguration Create(AsyncService service)
 {
     return new SimpleServerConfiguration();
 }
Exemple #22
0
        public async Task GetAsync()
        {
            var value = await AsyncService.GetAsync(3);

            Assert.AreEqual(3, value);
        }
Exemple #23
0
        static void Main(string[] args)
        {
            Console.WriteLine("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓");
            Console.WriteLine("┃                           ※服务器状态监控※                             ┃");
            Console.WriteLine("┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫");
            Console.WriteLine("┃                           Ver : 3.0 Release                              ┃");
            Console.WriteLine("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛");

            #region 读配置文件
            string  strPath  = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            IniFile mIniFile = new IniFile(strPath + @"\Scheme\Scheme.INI");

            //片断 [SERVER]
            string strServer     = mIniFile.ReadValue("SERVER", "Address", "127.0.0.1");
            string strPort       = mIniFile.ReadValue("SERVER", "Port", "4020");
            string strMaxClient  = mIniFile.ReadValue("SERVER", "MaxClient", "10");
            string strBufferSize = mIniFile.ReadValue("SERVER", "Buffer", "4096");
            string strInterval   = mIniFile.ReadValue("SERVER", "Interval", "15000");
            //Console.WriteLine(strInterval.ToString());
            #endregion

            #region 重置用户信息
            strAnalyse = @"Server=192.168.24.132\sqlexpress;Database=gameReport;uid=sa; pwd=1234;";
            MSSQLOperate pResetVerify = new MSSQLOperate(strAnalyse);
            pResetVerify.Connect(false);
            pResetVerify.ExecuteQuery("UPDATE Member_Verify SET Verify_Status = 0, Verify_Session = 'N/A'");
            pResetVerify.GetResult(RecordStyle.NONE);
            #endregion

            //pNotesSession.Initialize("12341234");
            bool b_Control = false;

            #region 收取Notes信件
            double TimeInterval = 0;
            try
            {
                TimeInterval = Convert.ToDouble(strInterval);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            System.Timers.Timer t = new System.Timers.Timer(TimeInterval);
            t.Elapsed  += new System.Timers.ElapsedEventHandler(CheckMail);
            t.AutoReset = true;

            if (TimeInterval != 0)
            {
                t.Enabled = b_Control;
            }
            #endregion

            #region 移动Notes信件
            System.Timers.Timer tt = new System.Timers.Timer(TimeInterval + 500);
            tt.Elapsed  += new System.Timers.ElapsedEventHandler(MoveMail);
            tt.AutoReset = true;

            if (TimeInterval != 0)
            {
                tt.Enabled = b_Control;
            }
            #endregion

            #region 实时监控
            pRealTime           = new System.Timers.Timer(10000);
            pRealTime.Elapsed  += new System.Timers.ElapsedEventHandler(RealtimeWarning);
            pRealTime.AutoReset = true;
            pRealTime.Enabled   = true;
            #endregion

            #region 数据库连接监控
            Thread tConnectTime = new Thread(new ThreadStart(ConnectTime));
            tConnectTime.Start();
            #endregion

            #region 定时发送AU日志
            //pSendAuLog = new System.Timers.Timer(604800000);
            //pSendAuLog.Elapsed += new System.Timers.ElapsedEventHandler(SendAuLog);
            //pSendAuLog.AutoReset = true;
            //pSendAuLog.Enabled = b_Control;
            #endregion

            IPEndPoint  pServerPoint = new IPEndPoint(0, int.Parse(strPort));
            SocketEvent pEvent       = new SocketEvent(ServerEvent);
            pServer = new AsyncService(NetServiceType.HOST, pEvent);
            pServer.StarService(pServerPoint, CompressionType.DEFLATE, 1024);

            while (true)
            {
                Thread.Sleep(0);
                #region
                string[] strInput = Console.ReadLine().Trim().Split(" ".ToCharArray(), 2);

                if (strInput.Length > 0)
                {
                    switch (strInput[0])
                    {
                    case "/R":
                        pResetVerify = new MSSQLOperate(strAnalyse);
                        pResetVerify.Connect(false);
                        pResetVerify.ExecuteQuery("UPDATE Member_Verify SET Verify_Status = 0, Verify_Sign = 'N/A', Verify_Session = 'N/A' WHERE Verify_Nick = '" + strInput[1] + "'");
                        pResetVerify.GetResult(RecordStyle.NONE);

                        if (pResetVerify.AffectRow > 0)
                        {
                            Console.WriteLine("成功重置" + strInput[1] + "的登录信息!");
                        }
                        else
                        {
                            Console.WriteLine("重置" + strInput[1] + "的登录信息失败!");
                        }
                        break;

                    case "/C":
                        pResetVerify = new MSSQLOperate(strAnalyse);
                        pResetVerify.Connect(false);
                        pResetVerify.ExecuteQuery("UPDATE Member_Verify SET Verify_Status = 1, Verify_Session = 'N/A' WHERE Verify_Nick = '" + strInput[1] + "'");
                        pResetVerify.GetResult(RecordStyle.NONE);

                        if (pResetVerify.AffectRow > 0)
                        {
                            Console.WriteLine("成功锁定" + strInput[1] + "的登录信息!");
                        }
                        else
                        {
                            Console.WriteLine("锁定" + strInput[1] + "的登录信息失败!");
                        }
                        break;

                    case "reset":
                        Console.WriteLine("Please Input /R [NickName]");
                        break;

                    case "restart":
                        pServer.StopService();
                        Thread.Sleep(500);
                        pServer.StarService(pServerPoint, CompressionType.DEFLATE, 1024);
                        Console.WriteLine("Server Restarted");
                        break;

                    case "stop":
                        pServer.StopService();
                        return;

                    case "clear":
                        Console.Clear();
                        break;

                    default:
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("无效指令");
                        Console.ForegroundColor = ConsoleColor.Gray;
                        break;
                    }
                }
                #endregion
            }
        }
Exemple #24
0
        public async Task GetAsync()
        {
            var value = await AsyncService.GetAsync(1);

            Assert.Equal(1, value);
        }
Exemple #25
0
        void Update()
        {
            if (AsyncService.Loading())
            {
                return;
            }

            AsyncService.StartFrameTimer();


            if (AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_GENERATE_NEW_CHUNKS_DEADLINE))
            {
                Chunk newChunk = GeneratorService.GenerateNewChunk();
                if (newChunk != null)
                {
                    ChunkRepository.AddToProcessingChunkList(newChunk);
                }
            }

            int i = 0;

            while (AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_START_WORK_DEADLINE) &&
                   i < ChunkRepository.GetProcessingChunkListSize())
            {
                Chunk chunk = ChunkRepository.GetProcessingChunk(i);
                if (chunk == null)
                {
                    continue;
                }

                if (AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_FLUSH_MODIFICATIONS_DEADLINE))
                {
                    chunk.FlushModifications();
                }

                if (AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_FINISH_MESH_DEADLINE))
                {
                    RenderService.FinishMeshGeneration(chunk);
                }

                if (AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_GENERATE_MESH_DEADLINE) &&
                    AsyncService.ThreadQueueSize() < Configuration.PERFORMANCE_MAX_THREAD_QUEUE_SIZE)
                {
                    RenderService.GenerateMeshes(chunk); // Threaded
                }

                if (AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_MARK_CHUNKS_FOR_MESH_UPDATE_DEADLINE))
                {
                    RenderService.MarkSurroundingChunksForMeshUpdate(chunk);
                }

                if (AsyncService.FrameElapsedPercentageIsNotExceeded(Configuration.PERFORMANCE_GENERATE_BLOCKS_DEADLINE) &&
                    AsyncService.ThreadQueueSize() < Configuration.PERFORMANCE_MAX_THREAD_QUEUE_SIZE)
                {
                    chunk.GenerateBlocks(GetSeed()); // Threaded
                }

                if (chunk.IsFinishedProcessing())
                {
                    ChunkRepository.RemoveFromProcessingChunkList(chunk);
                }

                i++;
            }

            GeneratorService.UnloadDeadChunks();
            RenderService.CullChunks();

            int numberOfChunks = ChunkRepository.NumberOfChunks();

            for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++)
            {
                Chunk chunk = ChunkRepository.GetChunkAtIndex(chunkIndex);
                if (chunk.IsFinishedProcessing())
                {
                    Vector3 position;
                    position.x = chunk.WorldPosition().x *Chunk.SIZE;
                    position.y = chunk.WorldPosition().y *Chunk.SIZE;
                    position.z = chunk.WorldPosition().z *Chunk.SIZE;

                    float distance = Vector3.Distance(position, Camera.main.transform.position);
                    if (distance > fogDistance)
                    {
                        fogDistance = distance;
                    }
                }
            }
            SendMessage("UpdateFogDistance", fogDistance, SendMessageOptions.DontRequireReceiver);

            GeneratorService.CleanupOldChunks();
            AsyncService.RePrioritizeCPUMediatorWork();
            ChunkRepository.RePrioritizeSortProcessingChunkList();
            ChunkRepository.FlushProcessingChunkListModifications();

            if (Input.GetKeyDown(KeyCode.F12))
            {
                showDebugMenu = !showDebugMenu;
            }

            if (Input.GetKeyDown(KeyCode.F5))
            {
                SaveScreenshot();
            }

            if (Input.GetKeyDown(KeyCode.F9))
            {
                ChunkRepository.DumpProcessingChunkListDebugData();
            }

            if (Input.GetKeyDown(KeyCode.Escape))
            {
                Application.Quit();
            }
        }
        public async Task GetAsync()
        {
            var value = await AsyncService.GetAsync(2);

            Assert.That(value, Is.EqualTo(2));
        }