System.GC.Collect()

Here are the examples of the csharp api System.GC.Collect() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1893 Examples 7

19 View Source File : MelonMain.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

internal IEnumerator GCTime() {
            RuntimeHelpers.PrepareConstrainedRegionsNoOP();
            while (true) {
                long mem = Profiler.GetMonoUsedSizeLong();
                yield return new WaitForSeconds(15f);
                System.GC.Collect();
                GarbageCollector.CollectIncremental(0);
                long dif = mem - Profiler.GetMonoUsedSizeLong();
                MelonLogger.Msg($"{Math.Abs(dif/1024/1024)}MB collected");
                lastFrameMemory = mem;
            }
        }

19 View Source File : AssetManager.cs
License : MIT License
Project Creator : 404Lcc

public void UnloadAllreplacedets()
        {
            foreach (replacedetData item in replacedetDict.Values)
            {
                Unloadreplacedet(item);
            }
            Resources.UnloadUnusedreplacedets();
            replacedetDict.Clear();
            GC.Collect();
        }

19 View Source File : UMAGeneratorBuiltin.cs
License : Apache License 2.0
Project Creator : A7ocin

void Update()
		{
			if (CheckRenderTextures())
				return; // if render textures needs rebuild we'll not do anything else

			if (forceGarbageCollect > garbageCollectionRate)
			{
				GC.Collect();
				forceGarbageCollect = 0;
				if (garbageCollectionRate < 1) garbageCollectionRate = 1;
			}
			else
			{
				Work();
			}
		}

19 View Source File : ThroughputToFileBench.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static void Run()
        {
            var dir = Path.GetFullPath(Guid.NewGuid().ToString());
            Directory.CreateDirectory(dir);

            try
            {
                Console.WriteLine("Initializing...");

                BasicConfigurator.Configure(
                    new ZeroLogBasicConfiguration
                    {
                        Appenders = { new DateAndSizeRollingFileAppender(Path.Combine(dir, "Output")), },
                        LogEventQueueSize = 1000 * 4096 * 4,
                        LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
                    }
                );

                var log = LogManager.GetLogger(typeof(ThroughputToFileBench));
                var duration = TimeSpan.FromSeconds(10);

                Console.WriteLine("Starting...");

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

                var sw = Stopwatch.StartNew();
                long counter = 0;
                while (sw.Elapsed < duration)
                {
                    counter++;
                    log.Debug().Append("Counter is: ").Append(counter).Log();
                }

                Console.WriteLine($"Log events: {counter:N0}, Time to append: {sw.Elapsed}");
                Console.WriteLine("Flushing...");
                LogManager.Shutdown();
                Console.WriteLine($"Time to flush: {sw.Elapsed}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Directory.Delete(dir, true);
            }

            Console.WriteLine("Done");
        }

19 View Source File : OVROverlaySample.cs
License : MIT License
Project Creator : absurd-joy

void ClearObjects()
        {
            for (int i = 0; i < spawnedCubes.Count; i++)
            {
                DestroyImmediate(spawnedCubes[i]);
            }
            spawnedCubes.Clear();
            GC.Collect();
        }

19 View Source File : Navigator.cs
License : MIT License
Project Creator : ABTSoftware

public void GoBack()
        {
            var lastExampleView = _currentExample;

            _history.Undo();

            if (_history.Current is Example example)
            {
                Navigate(example);
                ServiceLocator.Container.Resolve<IModule>().CurrentExample = example;
            }
            else
            {
                Navigate((Guid)_history.Current);
            }

            ServiceLocator.Container.Resolve<IExampleViewModel>().BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false;
            ServiceLocator.Container.Resolve<IExampleViewModel>().ExportExampleViewModel.IsExportVisible = false;

            GoBackCommand.RaiseCanExecuteChanged();
            GoForwardCommand.RaiseCanExecuteChanged();
            NavigateToHomeCommand.RaiseCanExecuteChanged();

            if (CurrentExample is ExampleAppPage lastExamplePage)
            {
                // Required to release memory from last example 
                lastExamplePage.ViewModel = null;                
            }

            if (lastExampleView != null)
            {
                lastExampleView.View = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

19 View Source File : Navigator.cs
License : MIT License
Project Creator : ABTSoftware

public void GoForward()
        {
            var lastExampleView = _currentExample;
            _history.Redo();

            if (_history.Current is Example example)
            {
                Navigate(example);
                ServiceLocator.Container.Resolve<IModule>().CurrentExample = example;
            }
            else
            {
                Navigate((Guid)_history.Current);
            }

            ServiceLocator.Container.Resolve<IExampleViewModel>().ExportExampleViewModel.IsExportVisible = false;
            ServiceLocator.Container.Resolve<IExampleViewModel>().BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false;

            GoBackCommand.RaiseCanExecuteChanged();
            GoForwardCommand.RaiseCanExecuteChanged();
            NavigateToHomeCommand.RaiseCanExecuteChanged();

            if (CurrentExample is ExampleAppPage lastExamplePage)
            {
                // Required to release memory from last example 
                lastExamplePage.ViewModel = null;
            }

            if (lastExampleView != null)
            {
                lastExampleView.View = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

19 View Source File : Navigator.cs
License : MIT License
Project Creator : ABTSoftware

private void OnExamplesFrameBeforeNavigation()
        {
            if (_currentExample != null)
            {
                _currentExample.View = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
        }

19 View Source File : Navigator.cs
License : MIT License
Project Creator : ABTSoftware

private void GoToHome()
        {
            var lastExampleView = _currentExample;

            Instance.Navigate(AppPage.HomePageId);
            _history.Push(AppPage.HomePageId);

            ServiceLocator.Container.Resolve<IExampleViewModel>().BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false;
            ServiceLocator.Container.Resolve<IExampleViewModel>().ExportExampleViewModel.IsExportVisible = false;
            ServiceLocator.Container.Resolve<IMainWindowViewModel>().HideSearchCommand.Execute(null);

            // Clears memory on going to home
            ((TransitioningFrame)_examplesFrame.Frame).SetContentNull();

            if (CurrentExample is ExampleAppPage lastExamplePage)
            {
                // Required to release memory from last example 
                lastExamplePage.ViewModel = null;
            }

            if (lastExampleView != null)
            {
                lastExampleView.View = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

19 View Source File : TestCase.cs
License : MIT License
Project Creator : ABTSoftware

public void Run(Action<double> completed)
        {
            //Arction added memory garbage collecting 
            GC.Collect();
            GC.WaitForPendingFinalizers(); 
            
            _speedTest.Execute(_args, _duration, completed);
        }

19 View Source File : MainViewModel.cs
License : MIT License
Project Creator : ABTSoftware

private void TestFinished(TestCase testCase, double result)
        {
            testCase.Dispose();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            
            RunNextTest();
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Main(string[] args)
        {
            var consolereplacedle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";

            Console.replacedle = consolereplacedle;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

            // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
            // We do this because almost all of the client/user input/output code does not take culture into account, and replacedumes en-US formatting.
            // Without this, many commands that require special characters like , and . will break
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            // Look for the log4net.config first in the current environment directory, then in the Executingreplacedembly location
            var exeLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var containerConfigDirectory = "/ace/Config";
            var log4netConfig = Path.Combine(exeLocation, "log4net.config");
            var log4netConfigExample = Path.Combine(exeLocation, "log4net.config.example");
            var log4netConfigContainer = Path.Combine(containerConfigDirectory, "log4net.config");

            if (IsRunningInContainer && File.Exists(log4netConfigContainer))
                File.Copy(log4netConfigContainer, log4netConfig, true);

            var log4netFileInfo = new FileInfo("log4net.config");
            if (!log4netFileInfo.Exists)
                log4netFileInfo = new FileInfo(log4netConfig);

            if (!log4netFileInfo.Exists)
            {
                var exampleFile = new FileInfo(log4netConfigExample);
                if (!exampleFile.Exists)
                {
                    Console.WriteLine("log4net Configuration file is missing.  Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
                    throw new Exception("missing log4net configuration file");
                }
                else
                {
                    if (!IsRunningInContainer)
                    {
                        Console.WriteLine("log4net Configuration file is missing,  cloning from example file.");
                        File.Copy(log4netConfigExample, log4netConfig);
                    }
                    else
                    {                        
                        if (!File.Exists(log4netConfigContainer))
                        {
                            Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                            var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
                            File.Copy(log4netConfigDocker, log4netConfig);
                            File.Copy(log4netConfigDocker, log4netConfigContainer);
                        }
                        else
                        {
                            File.Copy(log4netConfigContainer, log4netConfig);
                        }

                    }
                }
            }

            var logRepository = LogManager.GetRepository(replacedembly.GetEntryreplacedembly());
            XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);

            if (Environment.ProcessorCount < 2)
                log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");

            // Do system specific initializations here
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
                    MM_BeginPeriod(1);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }

            log.Info("Starting ACEmulator...");

            if (IsRunningInContainer)
                log.Info("ACEmulator is running in a container...");
            
            var configFile = Path.Combine(exeLocation, "Config.js");
            var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");

            if (IsRunningInContainer && File.Exists(configConfigContainer))
                File.Copy(configConfigContainer, configFile, true);

            if (!File.Exists(configFile))
            {
                if (!IsRunningInContainer)
                    DoOutOfBoxSetup(configFile);
                else
                {
                    if (!File.Exists(configConfigContainer))
                    {
                        DoOutOfBoxSetup(configFile);
                        File.Copy(configFile, configConfigContainer);
                    }
                    else
                        File.Copy(configConfigContainer, configFile);
                }
            }

            log.Info("Initializing ConfigManager...");
            ConfigManager.Initialize();

            if (ConfigManager.Config.Server.WorldName != "ACEmulator")
            {
                consolereplacedle = $"{ConfigManager.Config.Server.WorldName} | {consolereplacedle}";
                Console.replacedle = consolereplacedle;
            }

            if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
            {
                log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
                ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
                log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
            }

            if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
            {
                log.Info($"Purging orphaned biotas...");
                ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
                log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromFriendLists)
            {
                log.Info($"Pruning invalid friends from all friend lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromFriendLists(out var numberOfFriendsPruned);
                log.Info($"Pruned {numberOfFriendsPruned:N0} invalid friends found on friend lists.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedObjectsFromShortcutBars)
            {
                log.Info($"Pruning invalid shortcuts from all shortcut bars...");
                ShardDatabaseOfflineTools.PruneDeletedObjectsFromShortcutBars(out var numberOfShortcutsPruned);
                log.Info($"Pruned {numberOfShortcutsPruned:N0} deleted objects found on shortcut bars.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromSquelchLists)
            {
                log.Info($"Pruning invalid squelches from all squelch lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromSquelchLists(out var numberOfSquelchesPruned);
                log.Info($"Pruned {numberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists.");
            }

            if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
            {
                CheckForWorldDatabaseUpdate();

                if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
                    AutoApplyWorldCustomizations();
            }
            else
                log.Info($"AutoUpdateWorldDatabase is disabled...");

            if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
                AutoApplyDatabaseUpdates();
            else
                log.Info($"AutoApplyDatabaseUpdates is disabled...");

            // This should only be enabled manually. To enable it, simply uncomment this line
            //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);

            ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();

            // pre-load starterGear.json, abort startup if file is not found as it is required to create new characters.
            if (Factories.StarterGearFactory.GetStarterGearConfiguration() == null)
            {
                log.Fatal("Unable to load or parse starterGear.json. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Initializing ServerManager...");
            ServerManager.Initialize();

            log.Info("Initializing DatManager...");
            DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);

            log.Info("Initializing DatabaseManager...");
            DatabaseManager.Initialize();

            if (DatabaseManager.InitializationFailure)
            {
                log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Starting DatabaseManager...");
            DatabaseManager.Start();

            log.Info("Starting PropertyManager...");
            PropertyManager.Initialize();

            log.Info("Initializing GuidManager...");
            GuidManager.Initialize();

            if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
            {
                log.Info("Server Performance Monitor auto starting...");
                ServerPerformanceMonitor.Start();
            }

            if (ConfigManager.Config.Server.WorldDatabasePrecaching)
            {
                log.Info("Precaching Weenies...");
                DatabaseManager.World.CacheAllWeenies();
                log.Info("Precaching Cookbooks...");
                DatabaseManager.World.CacheAllCookbooks();
                log.Info("Precaching Events...");
                DatabaseManager.World.GetAllEvents();
                log.Info("Precaching House Portals...");
                DatabaseManager.World.CacheAllHousePortals();
                log.Info("Precaching Points Of Interest...");
                DatabaseManager.World.CacheAllPointsOfInterest();
                log.Info("Precaching Spells...");
                DatabaseManager.World.CacheAllSpells();
                log.Info("Precaching Treasures - Death...");
                DatabaseManager.World.CacheAllTreasuresDeath();
                log.Info("Precaching Treasures - Material Base...");
                DatabaseManager.World.CacheAllTreasureMaterialBase();
                log.Info("Precaching Treasures - Material Groups...");
                DatabaseManager.World.CacheAllTreasureMaterialGroups();
                log.Info("Precaching Treasures - Material Colors...");
                DatabaseManager.World.CacheAllTreasureMaterialColor();
                log.Info("Precaching Treasures - Wielded...");
                DatabaseManager.World.CacheAllTreasureWielded();
            }
            else
                log.Info("Precaching World Database Disabled...");

            log.Info("Initializing PlayerManager...");
            PlayerManager.Initialize();

            log.Info("Initializing HouseManager...");
            HouseManager.Initialize();

            log.Info("Initializing InboundMessageManager...");
            InboundMessageManager.Initialize();

            log.Info("Initializing SocketManager...");
            SocketManager.Initialize();

            log.Info("Initializing WorldManager...");
            WorldManager.Initialize();

            log.Info("Initializing EventManager...");
            EventManager.Initialize();

            // Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
            log.Info("Forcing .net garbage collection...");
            for (int i = 0 ; i < 10 ; i++)
                GC.Collect();

            // This should be last
            log.Info("Initializing CommandManager...");
            CommandManager.Initialize();

            if (!PropertyManager.GetBool("world_closed", false).Item)
            {
                WorldManager.Open(null);
            }
        }

19 View Source File : MemoryEventBusProvider.cs
License : MIT License
Project Creator : ad313

public void SubscribeQueue<T>(string key, int length, int delay, ExceptionHandlerEnum exceptionHandler, Func<List<T>, Task> handler, Func<Exception, List<T>, Task> error = null, Func<Task> completed = null)
        {
            if (length <= 0)
                throw new Exception("length must be greater than zero");

            Subscribe<T>(key, async msg =>
            {
                if (!IsEnable(key))
                {
                    Console.WriteLine($"{DateTime.Now} 频道【{key}】 已关闭消费");
                    return;
                }

                var pages = GetTotalPagesFromQueue(key, length);

                var needGc = pages * length > 1000;

                while (pages > 0)
                {
                    var data = await GetQueueItemsAsync<T>(key, length);
                    if (!data.Any())
                        break;

                    Exception ex = null;

                    try
                    {
                        await handler.Invoke(data);
                    }
                    catch (Exception e)
                    {
                        ex = e;

                        if (await HandleException(key, exceptionHandler, data, e))
                        {
                            pages = 1;
                            return;
                        }
                    }
                    finally
                    {
                        if (ex != null && error != null)
                            await HandleError(key, data, error, ex);

                        if (completed != null && pages == 1)
                            await HandleCompleted(key, completed);
                    }

                    pages--;

                    if (pages == 0 && needGc)
                    {
                        GC.Collect();
                        Console.WriteLine("---------------gc-----------------");
                    }

                    if (delay > 0)
                        await Task.Delay(delay);
                }
            });
        }

19 View Source File : HandleCollector.cs
License : GNU General Public License v3.0
Project Creator : aduskin

internal void Add()
         {
            lock (this)
            {
               _handleCount++;
               var performCollect = NeedCollection();

               if (!performCollect)
               {
                  return;
               }
            }

            GC.Collect();

            var sleep = (100 - _deltaPercent) / 4;
            System.Threading.Thread.Sleep(sleep);
         }

19 View Source File : Block.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public Block Copy()
        {
            using (MemoryStream ms = new MemoryStream()) 
            {
                SharpSerializer s = new SharpSerializer(true);
                s.Serialize(this, ms);
                ms.Position = 0;
                Block block = (Block)s.Deserialize(ms);
                System.GC.Collect();
                return block;
            }
        }

19 View Source File : IocScope.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected override void OnDispose()
        {
            if (DisposeFunc != null)
            {
                foreach (var func in DisposeFunc)
                {
                    try
                    {
                        func();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
                Local.Value = null;
            }
            try
            {
                IocHelper.DisposeScope();
                _scope.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            GC.Collect();
        }

19 View Source File : LogRecorder.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static void WriteRecordLoop()
        {
            bool success = true;
            try
            {
                if (Interlocked.Increment(ref BackIsRuning) > 1)
                {
                    return;
                }

                SystemTrace(LogLevel.System, "日志开始");
                int cnt = 0;
                while (State != LogRecorderStatus.Shutdown)
                {
                    //Thread.Sleep(10);//让子弹飞一会
                    if (State < LogRecorderStatus.Initialized || !BaseRecorder.IsInitialized || !Recorder.IsInitialized)
                    {
                        Thread.Sleep(50);
                        continue;
                    }

                    var array = RecordInfos.Switch();
                    if (array.Count == 0)
                    {
                        Thread.Sleep(50);
                        continue;
                    }

                    foreach (var info in array)
                    {
                        if (info == null)
                            continue;
                        try
                        {
                            info.Index = ++_id;
                            if (_id == ulong.MaxValue)
                                _id = 1;
                            if (!_isTextRecorder && (info.Type >= LogType.System || info.Local))
                                BaseRecorder.RecordLog(info);
                            if (Listener != null || TraceToConsole)
                                DoTrace(info);

                        }
                        catch (Exception ex)
                        {
                            SystemTrace(LogLevel.Error, "日志写入发生错误", ex);
                        }
                    }

                    try
                    {
                        Recorder.RecordLog(array.ToList());
                    }
                    catch (Exception ex)
                    {
                        SystemTrace(LogLevel.Error, "日志写入发生错误", ex);
                    }

                    if (++cnt < 1024)
                        continue;
                    GC.Collect();
                    cnt = 0;
                }
                _syncSlim.Release();
            }
            catch (Exception e)
            {
                success = false;
                Console.WriteLine(e);
            }
            finally
            {
                Interlocked.Decrement(ref BackIsRuning);
                SystemTrace(LogLevel.System, "日志结束");
            }
            if (!success)
                NewRecorderThread();
        }

19 View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static void OnZeroEnd()
        {
            RaiseEvent(ZeroNetEventType.AppStop);
            using (OnceScope.CreateScope(ZeroObjects))
            {
                ZeroTrace.SystemLog("[OnZeroEnd>>");
                SystemManager.Instance.HeartLeft();
                ApplicationState = StationState.Closing;
                if (HaseActiveObject)
                {
                    Parallel.ForEach(ActiveObjects.ToArray(), obj =>
                    {
                        try
                        {
                            ZeroTrace.SystemLog(obj.Name, "*Close");
                            obj.OnZeroEnd();
                        }
                        catch (Exception e)
                        {
                            ZeroTrace.WriteException(obj.Name, e, "*Close");
                        }
                    });
                    WaitAllObjectSemapreplaced();
                }
                GC.Collect();
                ApplicationState = StationState.Closed;
                ZeroTrace.SystemLog("<<OnZeroEnd]");
            }
        }

19 View Source File : IZeroObject.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

internal static void OnZeroDestory()
        {
            if (!Monitor.TryEnter(ZeroObjects))
                return;
            ZeroTrace.SystemLog("[OnZeroDestory>>");
            RaiseEvent(ZeroNetEventType.AppEnd);
            using (OnceScope.CreateScope(ZeroObjects))
            {
                var array = ZeroObjects.Values.ToArray();
                ZeroObjects.Clear();
                Parallel.ForEach(array, obj =>
                {
                    try
                    {
                        ZeroTrace.SystemLog(obj.Name, "*Destory");
                        obj.OnZeroDestory();
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Destory");
                    }
                });

                GC.Collect();
                ZeroTrace.SystemLog("<<OnZeroDestory]");

                ZeroTrace.SystemLog("[OnZeroDispose>>");
                Parallel.ForEach(array, obj =>
                {
                    try
                    {
                        ZeroTrace.SystemLog(obj.Name, "*Dispose");
                        obj.Dispose();
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Dispose");
                    }
                });
                ZeroTrace.SystemLog("<<OnZeroDispose]");
            }
        }

19 View Source File : ZeroStation.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private void Run()
        {
            bool success;
            using (OnceScope.CreateScope(this, OnRun, OnStop))
            {
                try
                {
                    success = RunInner(RunTaskCancel.Token);
                }
                catch (Exception e)
                {
                    ZeroTrace.WriteException(StationName, e, "Run");
                    success = false;
                }
            }
            if (ZeroApplication.CanDo && !success)
            {
                //自动重启
                ZeroTrace.SystemLog(StationName, "ReStart");
                Task.Factory.StartNew(Start);
            }
            else
            {
                _waitToken.Release();
            }

            GC.Collect();
        }

19 View Source File : Tester.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void Count()
        {
            TimeSpan ts = TimeSpan.FromTicks(RunTime);
            GC.Collect();
            ZeroTrace.SystemLog("Count", ExCount,
                $"{ts.TotalMilliseconds / ExCount}ms | {ExCount / (DateTime.Now - Start).TotalSeconds}/s",
                "Error", $"net:{NetError:D8} | worker:{WkError:D8} | time out:{TmError:D8} | bug:{BlError:D8}");
        }

19 View Source File : ZeroApplication.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void Shutdown()
        {
            ZeroTrace.SystemLog("Begin shutdown...");
            switch (ApplicationState)
            {
                case StationState.Destroy:
                    return;
                case StationState.BeginRun:
                case StationState.Run:
                    OnZeroEnd();
                    break;
                case StationState.Failed:
                    SystemManager.Instance.HeartLeft();
                    break;
            }
            ApplicationState = StationState.Destroy;
            if (GlobalObjects.Count > 0)
                GlobalSemapreplaced.Wait();
            OnZeroDestory();
            SystemManager.Instance.Destroy();
            LogRecorder.Shutdown();
            SystemMonitor.WaitMe();
            GC.Collect();
            ZContext.Destroy();
            ZeroTrace.SystemLog("Application shutdown ,see you late.");
            ApplicationState = StationState.Disposed;
            WaitToken.Release();
        }

19 View Source File : BatchPublisher.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected sealed override bool RunInner(CancellationToken token)
        {
            _socket = ZSocket.CreateRequestSocket(Config.RequestAddress, Idenreplacedy);
            SystemManager.Instance.HeartReady(StationName, RealName);
            State = StationState.Run;
            int cnt = 0;

            while (CanLoop)
            {
                Thread.Sleep(10);
                if (token.IsCancellationRequested)
                    break;
                if (++cnt == 36)
                {
                    GC.Collect();
                    cnt = 0;
                }
                var array = Items.Switch();
                if (array == null)
                {
                    Thread.Sleep(10);
                    continue;
                }
                if (TsonOperator == null)
                {
                    do
                    {
                        var datas = array.Count > 300 ? array.Take(255).ToArray() : array.ToArray();
                        while (!_socket.Publish(Name, datas) && CanLoop)
                            Thread.Sleep(10);
                        if (array.Count > 300)
                            array.RemoveRange(0, 255);
                    } while (array.Count > 300);
                    continue;
                }

                int idx = 0;
                while (idx < array.Count)
                {
                    byte[] buf;
                    using (TsonSerializer serializer = new TsonSerializer(TsonDataType.Array))
                    {
                        serializer.WriteType(TsonDataType.Object);
                        int size = array.Count - idx;
                        if (size > 255)
                            size = 255;
                        serializer.WriteLen(size);
                        for (; size > 0 && idx < array.Count; idx++, --size)
                        {
                            if (array[idx] == null)
                            {
                                serializer.WriteType(TsonDataType.Empty);
                                continue;
                            }
                            using (TsonObjectSerializeScope.CreateScope(serializer))
                            {
                                if (array[idx] != null)
                                    TsonOperator.ToTson(serializer, array[idx]);
                            }
                        }
                        buf = serializer.Close();
                    }
                    while (!_socket.Publish(ZeroPublishExtend.PubDescriptionTson2, Name, array.Count.ToString(), buf) && CanLoop)
                        Thread.Sleep(10);
                }
            }
            SystemManager.Instance.HeartLeft(StationName, RealName);
            _socket.TryClose();
            return true;
        }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : Aggrathon

public static void ClearMemory()
	{
		System.GC.Collect();
		Resources.UnloadUnusedreplacedets();
	}

19 View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

static int DrawLegend(Font font, Graphics imageGraphic)
		{
			if (FormMaster.legendItems.Count == 0)
			{
				return 0;
			}

			Dictionary<int, string> overridingLegendText = FormMaster.GatherOverriddenLegendTexts();
			List<int> drawnGroups = new List<int>();

			// Calculate the total height of all legend strings with their plot icons beside, combined
			int legendTotalHeight = 0;
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				// Skip legend groups that are merged/overridden and have already been accounted for
				if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
				{
					continue;
				}

				legendTotalHeight += Math.Max(
					(int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height),
					SettingsPlot.IsIconOrTopographic() ? SettingsPlotIcon.iconSize : 0);

				drawnGroups.Add(mapItem.legendGroup);
			}

			int skippedLegends = 0; // How many legend items did not fit onto the map

			// The initial Y coord where first legend item should be written, in order to Y-center the entire legend
			int legendCaretHeight = (mapDimension / 2) - (legendTotalHeight / 2);

			// Reset the drawn groups list, as we need to iterate over the items again
			drawnGroups = new List<int>();

			// Loop over every MapItem and draw the legend
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				// Skip legend groups that are merged/overridden and have already been drawn
				if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
				{
					continue;
				}

				// Calculate positions and color for legend text (plus icon)
				int fontHeight = (int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height);

				PlotIcon icon = mapItem.GetIcon();
				Image plotIconImg = SettingsPlot.IsIconOrTopographic() ? icon.GetIconImage() : null;

				Color legendColor = SettingsPlot.IsTopographic() ? SettingsPlotTopograph.legendColor : mapItem.GetLegendColor();
				Brush textBrush = new SolidBrush(legendColor);

				int iconHeight = SettingsPlot.IsIconOrTopographic() ?
					plotIconImg.Height :
					0;

				int legendHeight = Math.Max(fontHeight, iconHeight);

				// If the icon is taller than the text, offset the text it so it sits Y-centrally against the icon
				int textOffset = 0;
				if (iconHeight > fontHeight)
				{
					textOffset = (iconHeight - fontHeight) / 2;
				}

				// If the legend text/item fits on the map vertically
				if (legendCaretHeight > 0 && legendCaretHeight + legendHeight < mapDimension)
				{
					if (SettingsPlot.IsIconOrTopographic())
					{
						imageGraphic.DrawImage(plotIconImg, (float)(legendIconX - (plotIconImg.Width / 2d)), (float)(legendCaretHeight - (plotIconImg.Height / 2d) + (legendHeight / 2d)));
					}

					imageGraphic.DrawString(mapItem.GetLegendText(false), font, textBrush, new RectangleF(legendXMin, legendCaretHeight + textOffset, legendWidth, legendHeight));
				}
				else
				{
					skippedLegends++;
				}

				drawnGroups.Add(mapItem.legendGroup);
				legendCaretHeight += legendHeight; // Move the 'caret' down for the next item, enough to fit the icon and the text
			}

			GC.Collect();
			return skippedLegends;
		}

19 View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

static void DrawCellBackground(Graphics backgroundLayer)
		{
			if (!SettingsMap.IsCellModeActive())
			{
				return;
			}

			CellScaling cellScaling = SettingsCell.GetCell().GetScaling();

			int outlineWidth = SettingsCell.outlineWidth;
			int outlineSize = SettingsCell.outlineSize;

			Image plotIconImg = new Bitmap(outlineSize, outlineSize);
			Graphics plotIconGraphic = Graphics.FromImage(plotIconImg);
			plotIconGraphic.SmoothingMode = SmoothingMode.AntiAlias;
			Color outlineColor = Color.FromArgb(SettingsCell.outlineAlpha, SettingsCell.outlineColor);
			Pen outlinePen = new Pen(outlineColor, outlineWidth);
			plotIconGraphic.DrawEllipse(
				outlinePen,
				new RectangleF(outlineWidth, outlineWidth, outlineSize - (outlineWidth * 2), outlineSize - (outlineWidth * 2)));

			// Iterate over every data point and draw it
			foreach (MapDataPoint point in DataHelper.GetAllCellCoords(SettingsCell.GetCell().formID))
			{
				// If this coordinate exceeds the user-selected cell mapping height bounds, skip it
				// (Also accounts for the z-height of volumes)
				if (point.z < SettingsCell.GetMinHeightCoordBound() || point.z > SettingsCell.GetMaxHeightCoordBound())
				{
					continue;
				}

				point.x += cellScaling.xOffset;
				point.y += cellScaling.yOffset;

				// Multiply the coordinates by the scaling, but multiply around 0,0
				point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
				point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
				point.boundX *= cellScaling.scale;
				point.boundY *= cellScaling.scale;

				backgroundLayer.DrawImage(plotIconImg, (float)(point.x - (plotIconImg.Width / 2d)), (float)(point.y - (plotIconImg.Height / 2d)));
			}

			GC.Collect();
		}

19 View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public static void Reset()
		{
			SettingsMap.brightness = SettingsMap.brightnessDefault;
			SettingsMap.layerMilitary = false;
			SettingsMap.grayScale = false;

			DrawBaseLayer();
			GC.Collect();
			GC.WaitForPendingFinalizers();
		}

19 View Source File : Preprocessor.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

static void GenericClose(CSVFile file)
		{
			file.Validate();
			Directory.CreateDirectory(outputPathx64);
			file.WriteToFile(outputPathx64 + "//");

			file.rows = null;
			GC.Collect();

			Console.WriteLine(file.fileName + " done.");
		}

19 View Source File : Dashboard.cs
License : GNU General Public License v3.0
Project Creator : AHosseinRnj

private void ConnectBtn_Click(object sender, EventArgs e)
        {
            if (CountriesCmBox.SelectedIndex == 0)
            {
                MessageBox.Show("Please Select a Location", "Error at 0x53", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (!PPTP_rBtn.Checked && !L2TP_rBtn.Checked)
                {
                    MessageBox.Show("Please Select a Protocol", "Error at 0x59", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    VPN.setParameters(serverIP, adapterName, userName, preplacedWord, selectedProtocol, preSharedKey);
                    try
                    {
                        VPN.Connect();
                    }
                    finally
                    {
                        ConnectBtn_Enabled_False();
                        DisconnectBtn_Enabled_True();
                        CountriesCmBox_Enabled_False();
                        statusPicbox.Image = Properties.Resources.Connectpic;
                        GC.Collect();
                    }
                }
            }
        }

19 View Source File : Dashboard.cs
License : GNU General Public License v3.0
Project Creator : AHosseinRnj

private void DisconnectBtn_Click(object sender, EventArgs e)
        {
            try
            {
                VPN.Disconnect();
            }
            finally
            {
                ConnectBtn_Enabled_True();
                DisconnectBtn_Enabled_False();
                CountriesCmBox_Enabled_True();
                statusPicbox.Image = Properties.Resources.Disconnectpic;
                GC.Collect();
            }
        }

19 View Source File : Dashboard.cs
License : GNU General Public License v3.0
Project Creator : AHosseinRnj

public void ExitMethod()
        {
            if (!ConnectBtn.Enabled)
            {
                MessageBox.Show("Please Disconnect First", "Error at 0x150", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                VPN.Dispose();
                VPN = null;
                GC.Collect();
                Application.Exit();
            }
        }

19 View Source File : GarbageCollectionSample.cs
License : The Unlicense
Project Creator : ahotko

private void ForceGarbageCollection()
        {
            var gc = new GarbageCollection();

            var gcBefore = new GarbageCollectionInfo();
            Console.WriteLine($"Before Garbage Collection: {gcBefore}");
            gc.MakeSomeGarbage();
            var gcAfterGeneratingGarbage = new GarbageCollectionInfo();
            Console.WriteLine($"After Generating Garbage: {gcAfterGeneratingGarbage}");

            GC.Collect(0);
            var gcAfterCleanupGen0 = new GarbageCollectionInfo();
            Console.WriteLine($"After Garbage Collection of Gen0: {gcAfterCleanupGen0}");

            GC.Collect(1);
            var gcAfterCleanupGen1 = new GarbageCollectionInfo();
            Console.WriteLine($"After Garbage Collection of Gen1: {gcAfterCleanupGen1}");

            GC.WaitForPendingFinalizers();
            GC.Collect(2);

            var gcAfterCleanupGen2 = new GarbageCollectionInfo();
            Console.WriteLine($"After Garbage Collection of Gen2: {gcAfterCleanupGen2}");

            GC.WaitForPendingFinalizers();
            GC.Collect();

            var gcAfterCleanup = new GarbageCollectionInfo();
            Console.WriteLine($"After Garbage Collection: {gcAfterCleanup}");
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ahuchjm

List<System.Drawing.Point> FindPicture(string subPic, string parPic, System.Drawing.Rectangle searchRect, byte errorRange, double matchRate = 0.9, bool isFindAll = false)
        {
            List<System.Drawing.Point> ListPoint = new List<System.Drawing.Point>();
            var subBitmap = new Bitmap(subPic);
            var parBitmap = new Bitmap(parPic);
            int subWidth = subBitmap.Width;
            int subHeight = subBitmap.Height;
            int parWidth = parBitmap.Width;
            int parHeight = parBitmap.Height;
            if (searchRect.IsEmpty)
            {
                searchRect = new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height);
            }

            var searchLeftTop = searchRect.Location;
            var searchSize = searchRect.Size;
            System.Drawing.Color startPixelColor = subBitmap.GetPixel(0, 0);
            var subData = subBitmap.LockBits(new System.Drawing.Rectangle(0, 0, subBitmap.Width, subBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var parData = parBitmap.LockBits(new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var byteArrarySub = new byte[subData.Stride * subData.Height];
            var byteArraryPar = new byte[parData.Stride * parData.Height];
            Marshal.Copy(subData.Scan0, byteArrarySub, 0, subData.Stride * subData.Height);
            Marshal.Copy(parData.Scan0, byteArraryPar, 0, parData.Stride * parData.Height);

            var iMax = searchLeftTop.Y + searchSize.Height - subData.Height;//行
            var jMax = searchLeftTop.X + searchSize.Width - subData.Width;//列

            int smallOffsetX = 0, smallOffsetY = 0;
            int smallStartX = 0, smallStartY = 0;
            int pointX = -1; int pointY = -1;
            for (int i = searchLeftTop.Y; i < iMax; i++)
            {
                for (int j = searchLeftTop.X; j < jMax; j++)
                {
                    //大图x,y坐标处的颜色值
                    int x = j, y = i;
                    int parIndex = i * parWidth * 4 + j * 4;
                    var colorBig = System.Drawing.Color.FromArgb(byteArraryPar[parIndex + 3], byteArraryPar[parIndex + 2], byteArraryPar[parIndex + 1], byteArraryPar[parIndex]);
                    ;
                    if (ColorAEqualColorB(colorBig, startPixelColor, errorRange))
                    {
                        smallStartX = x - smallOffsetX;//待找的图X坐标
                        smallStartY = y - smallOffsetY;//待找的图Y坐标
                        int sum = 0;//所有需要比对的有效点
                        int matchNum = 0;//成功匹配的点
                        for (int m = 0; m < subHeight; m++)
                        {
                            for (int n = 0; n < subWidth; n++)
                            {
                                int x1 = n, y1 = m;
                                int subIndex = m * subWidth * 4 + n * 4;
                                var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);

                                sum++;
                                int x2 = smallStartX + x1, y2 = smallStartY + y1;
                                int parReleativeIndex = y2 * parWidth * 4 + x2 * 4;//比对大图对应的像素点的颜色
                                var colorPixel = System.Drawing.Color.FromArgb(byteArraryPar[parReleativeIndex + 3], byteArraryPar[parReleativeIndex + 2], byteArraryPar[parReleativeIndex + 1], byteArraryPar[parReleativeIndex]);
                                if (ColorAEqualColorB(colorPixel, color, errorRange))
                                {
                                    matchNum++;
                                }
                            }
                        }
                        if ((double)matchNum / sum >= matchRate)
                        {
                            Console.WriteLine((double)matchNum / sum);
                            pointX = smallStartX + (int)(subWidth / 2.0);
                            pointY = smallStartY + (int)(subHeight / 2.0);
                            var point = new System.Drawing.Point(pointX, pointY);
                            if (!ListContainsPoint(ListPoint, point, 10))
                            {
                                ListPoint.Add(point);
                            }
                            if (!isFindAll)
                            {
                                goto FIND_END;
                            }
                        }
                    }
                    //小图x1,y1坐标处的颜色值
                }
            }
        FIND_END:
            subBitmap.UnlockBits(subData);
            parBitmap.UnlockBits(parData);
            subBitmap.Dispose();
            parBitmap.Dispose();
            GC.Collect();
            return ListPoint;
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ahuchjm

List<NumBody> FindText(string subPic, string parPic, System.Drawing.Rectangle searchRect, byte errorRange, double matchRate = 0.9, bool isFindAll = false)
        {

            List<NumBody> ListPoint = new List<NumBody>();
            var subBitmap = new Bitmap(subPic);
            var parBitmap = new Bitmap(parPic);
            int subWidth = subBitmap.Width;
            int subHeight = subBitmap.Height;
            int parWidth = parBitmap.Width;
            int parHeight = parBitmap.Height;
            var bgColor = subBitmap.GetPixel(0, 0);//背景红色
            if (searchRect.IsEmpty)
            {
                searchRect = new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height);
            }
            var searchLeftTop = searchRect.Location;
            var searchSize = searchRect.Size;
            var subData = subBitmap.LockBits(new System.Drawing.Rectangle(0, 0, subBitmap.Width, subBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var parData = parBitmap.LockBits(new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var byteArrarySub = new byte[subData.Stride * subData.Height];
            var byteArraryPar = new byte[parData.Stride * parData.Height];
            Marshal.Copy(subData.Scan0, byteArrarySub, 0, subData.Stride * subData.Height);
            Marshal.Copy(parData.Scan0, byteArraryPar, 0, parData.Stride * parData.Height);
            var iMax = searchLeftTop.Y + searchSize.Height - subData.Height;//行
            var jMax = searchLeftTop.X + searchSize.Width - subData.Width;//列
            System.Drawing.Color startPixelColor = System.Drawing.Color.FromArgb(0, 0, 0);
            int smallOffsetX = 0, smallOffsetY = 0;
            int smallStartX = 0, smallStartY = 0;
            int pointX = -1; int pointY = -1;


            for (int m = 0; m < subHeight; m++)
            {
                for (int n = 0; n < subWidth; n++)
                {
                    smallOffsetX = n;
                    smallOffsetY = m;
                    int subIndex = m * subWidth * 4 + n * 4;
                    var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);
                    if (!ColorAEqualColorB(color, bgColor, errorRange))
                    {
                        startPixelColor = color;
                        goto END;
                    }
                }
            }

        END:
            for (int i = searchLeftTop.Y; i < iMax; i++)
            {
                for (int j = searchLeftTop.X; j < jMax; j++)
                {
                    //大图x,y坐标处的颜色值
                    int x = j, y = i;
                    int parIndex = i * parWidth * 4 + j * 4;
                    var colorBig = System.Drawing.Color.FromArgb(byteArraryPar[parIndex + 3], byteArraryPar[parIndex + 2], byteArraryPar[parIndex + 1], byteArraryPar[parIndex]);
                    ;

                    List<System.Drawing.Point> myListPoint = new List<System.Drawing.Point>();
                    if (ColorAEqualColorB(colorBig, startPixelColor, errorRange))
                    {
                        smallStartX = x - smallOffsetX;//待找的图X坐标
                        smallStartY = y - smallOffsetY;//待找的图Y坐标
                        int sum = 0;//所有需要比对的有效点
                        int matchNum = 0;//成功匹配的点
                        for (int m = 0; m < subHeight; m++)
                        {
                            for (int n = 0; n < subWidth; n++)
                            {
                                int x1 = n, y1 = m;
                                int subIndex = m * subWidth * 4 + n * 4;
                                var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);
                                if (color != bgColor)
                                {
                                    sum++;
                                    int x2 = smallStartX + x1, y2 = smallStartY + y1;
                                    int parReleativeIndex = y2 * parWidth * 4 + x2 * 4;//比对大图对应的像素点的颜色
                                    var colorPixel = System.Drawing.Color.FromArgb(byteArraryPar[parReleativeIndex + 3], byteArraryPar[parReleativeIndex + 2], byteArraryPar[parReleativeIndex + 1], byteArraryPar[parReleativeIndex]);
                                    if (ColorAEqualColorB(colorPixel, color, errorRange))
                                    {
                                        matchNum++;
                                    }
                                    myListPoint.Add(new System.Drawing.Point(x2, y2));
                                }
                            }
                        }

                        double rate = (double)matchNum / sum;
                        if (rate>= matchRate)
                        {
                            Console.WriteLine((double)matchNum / sum);
                            pointX = smallStartX + (int)(subWidth / 2.0);
                            pointY = smallStartY + (int)(subHeight / 2.0);
                            var point = new System.Drawing.Point(pointX, pointY);
                            if (!ListTextBodyContainsPoint(ListPoint, point, 1))
                            {
                                ListPoint.Add(new NumBody() { point = point, matchNum = matchNum,matchSum=sum, matchRate = rate, bodyCollectionPoint = myListPoint });
                            }
                            SearchNumbersByMatchNum(ref ListPoint);
                            if (!isFindAll)
                            {
                                goto FIND_END;
                            }
                        }
                    }
                    //小图x1,y1坐标处的颜色值
                }
            }
        FIND_END:
            subBitmap.UnlockBits(subData);
            parBitmap.UnlockBits(parData);
            subBitmap.Dispose();
            parBitmap.Dispose();
            GC.Collect();
            return ListPoint;
        }

19 View Source File : Information.cs
License : GNU General Public License v3.0
Project Creator : AHosseinRnj

private void ExitBtn_Click(object sender, EventArgs e)
        {
            GC.Collect();
            this.Close();
        }

19 View Source File : ShadowMapCacheSystem.cs
License : Apache License 2.0
Project Creator : aivclab

public static void Dispose() {
      if (_instance == null) {
        //CustomDebug.Log("ShadowMapCacheSystem instance is null", DebugType.SettingMenus);
        return;
      }

      //CustomDebug.Log("Disposing ShadowMapCacheSystem", DebugType.SettingMenus);

      _disposed = true;
      SceneManager.sceneLoaded -= _instance.NewSceneLoaded;
      GC.Collect();
    }

19 View Source File : SteamVR_LoadLevel.cs
License : MIT License
Project Creator : ajayyy

IEnumerator LoadLevel()
	{
		// Optionally rotate loading screen transform around the camera into view.
		// We replacedume here that the loading screen is already facing toward the origin,
		// and that the progress bar transform (if any) is a child and will follow along.
		if (loadingScreen != null && loadingScreenDistance > 0.0f)
		{
			// Wait until we have tracking.
			var hmd = SteamVR_Controller.Input((int)OpenVR.k_unTrackedDeviceIndex_Hmd);
			while (!hmd.hasTracking)
				yield return null;

			var tloading = hmd.transform;
			tloading.rot = Quaternion.Euler(0.0f, tloading.rot.eulerAngles.y, 0.0f);
			tloading.pos += tloading.rot * new Vector3(0.0f, 0.0f, loadingScreenDistance);

			var t = loadingScreenTransform != null ? loadingScreenTransform : transform;
			t.position = tloading.pos;
			t.rotation = tloading.rot;
		}

		_active = this;

		SteamVR_Events.Loading.Send(true);

		// Calculate rate for fading in loading screen and progress bar.
		if (loadingScreenFadeInTime > 0.0f)
		{
			fadeRate = 1.0f / loadingScreenFadeInTime;
		}
		else
		{
			alpha = 1.0f;
		}

		var overlay = OpenVR.Overlay;

		// Optionally create our loading screen overlay.
		if (loadingScreen != null && overlay != null)
		{
			loadingScreenOverlayHandle = GetOverlayHandle("loadingScreen", loadingScreenTransform != null ? loadingScreenTransform : transform, loadingScreenWidthInMeters);
			if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
			{
				var texture = new Texture_t();
				texture.handle = loadingScreen.GetNativeTexturePtr();
				texture.eType = SteamVR.instance.textureType;
				texture.eColorSpace = EColorSpace.Auto;
				overlay.SetOverlayTexture(loadingScreenOverlayHandle, ref texture);
			}
		}

		bool fadedForeground = false;

		// Fade out to compositor
		SteamVR_Events.LoadingFadeOut.Send(fadeOutTime);

		// Optionally set a skybox to use as a backdrop in the compositor.
		var compositor = OpenVR.Compositor;
		if (compositor != null)
		{
			if (front != null)
			{
				SteamVR_Skybox.SetOverride(front, back, left, right, top, bottom);

				// Explicitly fade to the compositor since loading will cause us to stop rendering.
				compositor.FadeGrid(fadeOutTime, true);
				yield return new WaitForSeconds(fadeOutTime);
			}
			else if (backgroundColor != Color.clear)
			{
				// Otherwise, use the specified background color.
				if (showGrid)
				{
					// Set compositor background color immediately, and start fading to it.
					compositor.FadeToColor(0.0f, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, true);
					compositor.FadeGrid(fadeOutTime, true);
					yield return new WaitForSeconds(fadeOutTime);
				}
				else
				{
					// Fade the foreground color in (which will blend on top of the scene), and then cut to the compositor.
					compositor.FadeToColor(fadeOutTime, backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a, false);
					yield return new WaitForSeconds(fadeOutTime + 0.1f);
					compositor.FadeGrid(0.0f, true);
					fadedForeground = true;
				}
			}
		}

		// Now that we're fully faded out, we can stop submitting frames to the compositor.
		SteamVR_Render.pauseRendering = true;

		// Continue waiting for the overlays to fully fade in before continuing.
		while (alpha < 1.0f)
			yield return null;

		// Keep us from getting destroyed when loading the new level, otherwise this coroutine will get stopped prematurely.
		transform.parent = null;
		DontDestroyOnLoad(gameObject);

		if (!string.IsNullOrEmpty(internalProcessPath))
		{
			Debug.Log("Launching external application...");
			var applications = OpenVR.Applications;
			if (applications == null)
			{
				Debug.Log("Failed to get OpenVR.Applications interface!");
			}
			else
			{
				var workingDirectory = Directory.GetCurrentDirectory();
				var fullPath = Path.Combine(workingDirectory, internalProcessPath);
				Debug.Log("LaunchingInternalProcess");
				Debug.Log("ExternalAppPath = " + internalProcessPath);
				Debug.Log("FullPath = " + fullPath);
				Debug.Log("ExternalAppArgs = " + internalProcessArgs);
				Debug.Log("WorkingDirectory = " + workingDirectory);
				var error = applications.LaunchInternalProcess(fullPath, internalProcessArgs, workingDirectory);
				Debug.Log("LaunchInternalProcessError: " + error);
#if UNITY_EDITOR
				UnityEditor.EditorApplication.isPlaying = false;
#elif !UNITY_METRO
				System.Diagnostics.Process.GetCurrentProcess().Kill();
#endif
			}
		}
		else
		{
			var mode = loadAdditive ? UnityEngine.SceneManagement.LoadSceneMode.Additive : UnityEngine.SceneManagement.LoadSceneMode.Single;
			if (loadAsync)
			{
				Application.backgroundLoadingPriority = ThreadPriority.Low;
				async = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(levelName, mode);

				// Performing this in a while loop instead seems to help smooth things out.
				//yield return async;
				while (!async.isDone)
				{
					yield return null;
				}
			}
			else
			{
				UnityEngine.SceneManagement.SceneManager.LoadScene(levelName, mode);
			}
		}

		yield return null;

		System.GC.Collect();

		yield return null;

		Shader.WarmupAllShaders();

		// Optionally wait a short period of time after loading everything back in, but before we start rendering again
		// in order to give everything a change to settle down to avoid any hitching at the start of the new level.
		yield return new WaitForSeconds(postLoadSettleTime);

		SteamVR_Render.pauseRendering = false;

		// Fade out loading screen.
		if (loadingScreenFadeOutTime > 0.0f)
		{
			fadeRate = -1.0f / loadingScreenFadeOutTime;
		}
		else
		{
			alpha = 0.0f;
		}

		// Fade out to compositor
		SteamVR_Events.LoadingFadeIn.Send(fadeInTime);

		// Refresh compositor reference since loading scenes might have invalidated it.
		compositor = OpenVR.Compositor;
		if (compositor != null)
		{
			// Fade out foreground color if necessary.
			if (fadedForeground)
			{
				compositor.FadeGrid(0.0f, false);
				compositor.FadeToColor(fadeInTime, 0.0f, 0.0f, 0.0f, 0.0f, false);
				yield return new WaitForSeconds(fadeInTime);
			}
			else
			{
				// Fade scene back in, and reset skybox once no longer visible.
				compositor.FadeGrid(fadeInTime, false);
				yield return new WaitForSeconds(fadeInTime);

				if (front != null)
				{
					SteamVR_Skybox.ClearOverride();
				}
			}
		}

		// Finally, stick around long enough for our overlays to fully fade out.
		while (alpha > 0.0f)
			yield return null;

		if (overlay != null)
		{
			if (progressBarOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
				overlay.HideOverlay(progressBarOverlayHandle);
			if (loadingScreenOverlayHandle != OpenVR.k_ulOverlayHandleInvalid)
				overlay.HideOverlay(loadingScreenOverlayHandle);
		}

		Destroy(gameObject);

		_active = null;

		SteamVR_Events.Loading.Send(false);
	}

19 View Source File : FlowableDelayTest.cs
License : Apache License 2.0
Project Creator : akarnokd

[Test]
        public void RefLeak()
        {

            var wr = RunLeak();

            for (int i = 0; i < 5; i++)
            {
                GC.Collect();
                Thread.Sleep(100);
            }

            var c = Executors.Computation;

            replacedert.IsFalse(wr.TryGetTarget(out TestSubscriber<int> o));

            Console.WriteLine(c);
        }

19 View Source File : FileCollector.cs
License : MIT License
Project Creator : AkiniKites

private List<T> LoadInternal()
        {
            if (_useCache && _cache.TryLoadCache(out var cached))
            {
                if (cached.Any())
                    return cached;
            }
            else
            {
                cached = new List<T>();
            }

            var files = Prefetch.Load().Files.Keys;
            var bag = new ConcurrentBag<T>();

            var parallels = IoC.CmdOptions.SingleThread ? 1 : Environment.ProcessorCount;
            var tasks = new ParallelTasks<string>(
                parallels, file =>
                {
                    if (_fileNameValidator(file) && !_ignored.Any(x => x.IsMatch(file)))
                    {
                        foreach (var item in _itemGetter(file))
                            bag.Add(item);
                    }
                });

            tasks.Start();
            tasks.AddItems(files);
            tasks.WaitForComplete();

            GC.Collect();

            var itemList = bag.ToList();
            if (_consolidator != null)
                itemList = _consolidator(itemList).ToList();

            if (_useCache)
            {
                cached.AddRange(itemList);
                _cache.Save(cached);
            }

            return itemList;
        }

19 View Source File : AssetBundleFilesAnalyze.cs
License : MIT License
Project Creator : akof1314

public static void Clear()
        {
            if (sreplacedetBundleFileInfos != null)
            {
                sreplacedetBundleFileInfos.Clear();
                sreplacedetBundleFileInfos = null;
            }
            if (sreplacedetFileInfos != null)
            {
                sreplacedetFileInfos.Clear();
                sreplacedetFileInfos = null;
            }
            sreplacedyzeScene = null;

#if UNITY_5 || UNITY_5_3_OR_NEWER
            EditorUtility.UnloadUnusedreplacedetsImmediate();
#endif
            System.GC.Collect();
        }

19 View Source File : DelegateReferenceTests.cs
License : Apache License 2.0
Project Creator : AKruimink

[Fact]
        public async Task Construct_KeepReferenceAliveTrue_ShouldPreventGarbageCollection()
        {
            // Prepare
            Action referenceAction = () => { };
            var delegateReference = new DelegateReference(referenceAction, true);

            // Act
            referenceAction = null!;
            await Task.Delay(100);
            GC.Collect();

            // replacedert
            replacedert.NotNull(delegateReference.Delegate);
        }

19 View Source File : DelegateReferenceTests.cs
License : Apache License 2.0
Project Creator : AKruimink

[Fact]
        public async Task Construct_KeepReferenceAliveFalse_ShouldGetGarbageCollected()
        {
            // Prepare
            Action referenceAction = () => { };
            var delegateReference = new DelegateReference(referenceAction, false);

            // Act
            referenceAction = null!;
            await Task.Delay(100);
            GC.Collect();

            // replacedert
            replacedert.NotNull(delegateReference.Delegate);
        }

19 View Source File : DelegateReferenceTests.cs
License : Apache License 2.0
Project Creator : AKruimink

[Fact]
        public async Task GetDelegate_DelegateNotAlive_ShouldReturnNull()
        {
            // Prepare
            var clreplacedFixture = new ClreplacedFixture();
            var delegateReference = new DelegateReference((Action)clreplacedFixture.EmptyMethod, false);

            // Act
            clreplacedFixture = null!;
            await Task.Delay(100);
            GC.Collect();

            // replacedert
            replacedert.Null(delegateReference.Delegate);
        }

19 View Source File : DelegateReferenceTests.cs
License : Apache License 2.0
Project Creator : AKruimink

[Fact]
        public async Task DelegateEquals_EqualNullDelegateReferenceNotAlive_ShouldReturnTrue()
        {
            // Prepare
            var clreplacedFixture = new ClreplacedFixture();
            var weakReference = new WeakReference((Action)clreplacedFixture.EmptyMethod);
            var delegateReference = new DelegateReference((Action)clreplacedFixture.EmptyMethod, false);

            // Act
            clreplacedFixture = null!;
            await Task.Delay(100);
            GC.Collect();

            // replacedert
            replacedert.False(weakReference.IsAlive);
            replacedert.True(delegateReference.DelegateEquals(null!));
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

static void Tests2()
    {
        foreach (var warmup in new[] { true, false })
            for (int li = 0; li < 140; li++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();

                var uts = new UntypedBase[16];

                for (int i = 0; i < 16; i++)
                {
                    if(i % 2 == 0)
                        uts[i] = new Typed1();
                    else
                        uts[i] = new Typed2();
                }

                var its = new ISum[16];

                for (int i = 0; i < 16; i++)
                {
                    if (i % 2 == 0)
                        its[i] = new Typed1();
                    else
                        its[i] = new Typed2();
                }

                var dts = new NoVirt[16];

                for (int i = 0; i < 16; i++)
                {
                    if (i % 2 == 0)
                        dts[i] = new NoVirt();
                    else
                        dts[i] = new NoVirt();
                }

                Measure($"Interface", warmup, () =>
                {
                    int check = 0;
                    for (int i = 0; i < 1 << 20; i++)
                        check += its[i % 16].Sum();
                    return check;
                });

                Measure($"Cast", warmup, () =>
                {
                    int check = 0;
                    for (int i = 0; i < 1 << 20; i++)
                        check += uts[i % 16].CastSum();
                    return check;
                });

                Measure($"Uncast", warmup, () =>
                {
                    int check = 0;
                    for (int i = 0; i < 1 << 20; i++)
                        check += uts[i % 16].Sum();
                    return check;
                });

                Measure($"Decast", warmup, () =>
                {
                    int check = 0;
                    for (int i = 0; i < 1 << 20; i++)
                        check += uts[i % 16].Sum();
                    return check;
                });

                Measure($"Devirt", warmup, () =>
                {
                    int check = 0;
                    for (int i = 0; i < 1 << 20; i++)
                        check += dts[i % 16].Sum();
                    return check;
                });

            }


        foreach (var result in results_)
        {
            Console.WriteLine(
                $"Benchmarked avg of {result.Value.Count} samples totalling {result.Value.Average():F3} µs to {result.Key}");
        }
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR

private static void Tests1()
    {
        int keysCount = 1 << 15;
        int maxValue = 1 << 16;
        uint umaxValue = 1 << 16;

        int[] keys = new int[keysCount];
        uint[] ukeys = new uint[keysCount];

        var r = new Random(42);
        for (int i = 0; i < keysCount; i++)
        {
            keys[i] = r.Next(maxValue);
            ukeys[i] = (uint) keys[i];
        }

        foreach (var warmup in new[] {true, false})
            for (int li = 0; li < 40; li++)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();


                var dict = new Dictionary<int, int>();

                Measure($"Add to Dictionary", warmup, () =>
                {
                    for (int i = 0; i < keysCount; i++)
                        dict[keys[i]] = maxValue - keys[i];
                    return 0;
                });

                Measure($"Sum in Dictionary", warmup, () =>
                {
                    int checksum = 0;
                    for (int i = 0; i < keysCount; i++)
                        checksum += dict[keys[i]];
                    return checksum;
                });

                Measure($"Rem from Dictionary", warmup, () =>
                {
                    for (int i = 0; i < keysCount; i++)
                        dict.Remove(keys[i]);
                    return 0;
                });


                var sa = new SparseArray(16, 10);

                Measure($"Add to SparseArray", warmup, () =>
                {
                    for (int i = 0; i < keysCount; i++)
                        sa.Add(keys[i], maxValue - keys[i]);
                    return 0;
                });

                Measure($"Sum in SparseArray", warmup, () =>
                {
                    int checksum = 0;
                    for (int i = 0; i < keysCount; i++)
                        checksum += sa.Get(keys[i]);
                    return checksum;
                });

                //Measure($"Rem from SparseArray", warmup, () =>
                //{
                //    for (int i = 0; i < keysCount; i++)
                //        dict.Remove(keys[i]);
                //    return 0;
                //});


                var um = new UInt32UInt32Map();

                Measure($"Add to UInt32UInt32Map", warmup, () =>
                {
                    for (int i = 0; i < keysCount; i++)
                        um.GetRef(ukeys[i]) = (umaxValue - ukeys[i]);
                    return 0;
                });

                Measure($"Sum in UInt32UInt32Map", warmup, () =>
                {
                    uint checksum = 0;
                    for (int i = 0; i < keysCount; i++)
                        checksum += um.GetRef(ukeys[i]);
                    return checksum;
                });


                var im = new Int32Int32Map();

                Measure($"Add to Int32Int32Map", warmup, () =>
                {
                    for (int i = 0; i < keysCount; i++)
                        im.GetRef(keys[i]) = (maxValue - keys[i]);
                    return 0;
                });

                Measure($"Sum in Int32Int32Map", warmup, () =>
                {
                    int checksum = 0;
                    for (int i = 0; i < keysCount; i++)
                        checksum += im.GetRef(keys[i]);
                    return checksum;
                });


                /*
                var pool = new BufferPool(256).SpecializeFor<int>();
                QuickDictionary<int, int, Buffer<int>, Buffer<int>, Buffer<int>, PrimitiveComparer<int>>
                    .Create(pool, pool, pool, 2, 3, out var bdict);

                Measure($"Add to BepuDictionary", warmup, () =>
                {
                    for (int i = 0; i < keysCount; i++)
                        bdict.Add(keys[i], maxValue - keys[i], pool, pool, pool);
                    return 0;
                });

                Measure($"Sum in BepuDictionary", warmup, () =>
                {
                    int checksum = 0;
                    for (int i = 0; i < keysCount; i++)
                    {
                        bdict.TryGetValue(keys[i], out int value);
                        checksum +=  value;
                    }

                    return checksum;
                });

                Measure($"Rem from BepuDictionary", warmup, () =>
                {
                    for (int i = 0; i < keysCount; i++)
                        bdict.FastRemove(keys[i]);
                    return 0;
                });

                //dictionary.EnsureCapacity(dictionary.Count * 3, pool, pool, pool);
                //dictionary.Compact(pool, pool, pool);
                
                bdict.Dispose(pool, pool, pool);
                pool.Raw.Clear();
                */
            }


        foreach (var result in results_)
        {
            Console.WriteLine(
                $"Benchmarked avg of {result.Value.Count} samples totalling {result.Value.Average():F3} µs to {result.Key}");
        }


        //TestSetResizing<Buffer<int>, BufferPool<int>>(bufferPool);


        //var arrayPool = new ArrayPool<int>();
        //TestSetResizing<Array<int>, ArrayPool<int>>(arrayPool);
        //arrayPool.Clear();
    }

19 View Source File : Program.cs
License : MIT License
Project Creator : alexshtf

static void Main(string[] args)
        {
            Console.SetWindowSize(120, 30);

            int[] sizes = { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 };
            for (int i = 0; i < sizes.Length; ++i)
            {
                var termsCount = sizes[i];
                var varsCount = sizes[i];

                Console.WriteLine("Benchmark for {0} terms and {1} variables", termsCount, varsCount);

                Console.Write("\tConstructing coefficients ...");
                var coefficients = GenerateCoefficients(termsCount, varsCount);
                Console.WriteLine(" done");

                // generate variables
                var vars = new Variable[varsCount];
                for(int j = 0; j < sizes[i]; ++j)
                    vars[j] = new Variable();


                Console.Write("\tGenerating input data ...");
                double[][] inputData = new double[1000][];
                for (int j = 0; j < inputData.Length; ++j)
                    inputData[j] = RandomDoubles(varsCount);
                Console.WriteLine(" done");

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tConstructing compiled term ...");
                var stopWatch = Stopwatch.StartNew();
                var compiledTerm = ConstructTerm(coefficients, vars);
                stopWatch.Stop();
                Console.WriteLine(" done in {0} milliseconds", stopWatch.ElapsedMilliseconds);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking manual evaluation ...");
                stopWatch = Stopwatch.StartNew();
                double sum = 0;
                for (int j = 0; j < inputData.Length; ++j)
                    sum += NativeEvaluate(coefficients, inputData[j]);
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking gradient approximation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0;
                for (int j = 0; j < inputData.Length / 10; ++j)
                {
                    var gradient = ApproxGradient(coefficients, inputData[j]);
                    sum += gradient.Sum();
                }
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, 10 * stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking AutoDiff compiled evaluation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0;
                for (int j = 0; j < inputData.Length; ++j)
                    sum += compiledTerm.Evaluate(inputData[j]);
                stopWatch.Stop();
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

                GC.Collect();
                Thread.Sleep(4000);

                Console.Write("\tBenchmarking compiled differentiation ...");
                stopWatch = Stopwatch.StartNew();
                sum = 0; 
                for(int j = 0; j < inputData.Length; ++j)
                {
                    var diffResult = compiledTerm.Differentiate(inputData[j]);
                    sum += diffResult.Item2 + diffResult.Item1.Sum();
                }
                Console.WriteLine(" sum is {0}, speed is {1} msec/op", sum, stopWatch.ElapsedMilliseconds / (double)inputData.Length);

            }
        }

19 View Source File : OptimizerExecutor.cs
License : Apache License 2.0
Project Creator : AlexWan

private async void PrimeThreadWorkerPlace()
        {
            ReportsToFazes = new List<OptimazerFazeReport>();

            int countBots = BotCountOneFaze();

            SendLogMessage(OsLocalization.Optimizer.Message4 + countBots, LogMessageType.System);

            DateTime timeStart = DateTime.Now;

            _countAllServersMax = countBots;

            for (int i = 0; i < _master.Fazes.Count; i++)
            {
                if (_neadToStop)
                {
                    _primeThreadWorker = null;
                    TestReadyEvent?.Invoke(ReportsToFazes);
                    return;
                }

                if (_master.Fazes[i].TypeFaze == OptimizerFazeType.InSample)
                {
                    OptimazerFazeReport report = new OptimazerFazeReport();
                    report.Faze = _master.Fazes[i];

                    ReportsToFazes.Add(report);

                    StartAsuncBotFactoryInSample(countBots, _master.StrategyName, _master.IsScript, "InSample");
                    StartOptimazeFazeInSample(_master.Fazes[i], report, _parameters, _parametersOn);
                }
                else
                {

                    SendLogMessage("ReportsCount" + ReportsToFazes[ReportsToFazes.Count - 1].Reports.Count.ToString(), LogMessageType.System);

                    OptimazerFazeReport reportFiltred = new OptimazerFazeReport();
                    EndOfFazeFiltration(ReportsToFazes[ReportsToFazes.Count - 1], reportFiltred);

                    OptimazerFazeReport report = new OptimazerFazeReport();
                    report.Faze = _master.Fazes[i];

                    ReportsToFazes.Add(report);

                    StartAsuncBotFactoryOutOfSample(reportFiltred, _master.StrategyName, _master.IsScript, "OutOfSample");

                    StartOptimazeFazeOutOfSample(report, reportFiltred);
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            TimeSpan time = DateTime.Now - timeStart;

            SendLogMessage(OsLocalization.Optimizer.Message7, LogMessageType.System);
            SendLogMessage("Total test time = " + time.ToString(), LogMessageType.System);

            TestReadyEvent?.Invoke(ReportsToFazes);
            _primeThreadWorker = null;

            return;

        }

19 View Source File : Benchmark.cs
License : Apache License 2.0
Project Creator : alexyakunin

private void RunOnce()
        {
            if (MustWarmup) {
                Action.Invoke(true);
                SubtractAction?.Invoke(true);
                MustWarmup = false;
            }
            if (MustGC)
                GC.Collect();

            var elapsed = TimeSpan.Zero;
            
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try {
                Action.Invoke(false);
            }
            finally {
                stopwatch.Stop();
                elapsed += stopwatch.Elapsed;
            }

            if (SubtractAction != null) {
                if (MustGC)
                    GC.Collect();
                stopwatch.Reset();
                stopwatch.Start();
                try {
                    SubtractAction.Invoke(false);
                }
                finally {
                    stopwatch.Stop();
                    elapsed -= stopwatch.Elapsed * SubtractActionFactor;
                }
            }

            Timings.Add(elapsed);
        }

19 View Source File : BurnTester.cs
License : Apache License 2.0
Project Creator : alexyakunin

public void TryInitialize()
        {
            if (_isInitialized)
                return;
            
            _allocations = new (int, sbyte, sbyte) [AllocationSequenceLength];
            var sizeSampler = CreateSizeSampler(Random).Truncate(1, MaxSize);
            var timeSampler = CreateTimeSampler(Random).Truncate(0, MaxTime);
            var releaseCycleTimeInSeconds = 1.0 * GarbageHolder.TicksPerReleaseCycle / Stopwatch.Frequency;
            var timeFactor = TimeSamplerUnitInSeconds / releaseCycleTimeInSeconds;
            for (var i = 0; i < AllocationSequenceLength; i++) {
                var size = (int) sizeSampler.Sample();
                var arraySize = GarbageAllocator.ByteSizeToArraySize(size);
                
                var time = timeSampler.Sample();
                var timeStr = ((long) (time * timeFactor)).ToString();
                var bucketIndex = (sbyte) (timeStr.Length - 1);
                var generationIndex = (sbyte) (timeStr[0] - '0');
                
                _allocations[i] = (arraySize, bucketIndex, generationIndex);
            }

            _startIndexes = Enumerable.Range(0, ParallelRunner.ThreadCount)
                .Select(_ => Random.Next() % AllocationSequenceLength)
                .ToArray();
            
            // Creating _staticSet
            var startOffset = Random.Next() % AllocationSequenceLength;
            _staticSet = ParallelRunner.New(i => new SetAllocator(
                    StaticSetSize / ParallelRunner.ThreadCount,
                    _allocations,
                    (_startIndexes[i] + startOffset) % AllocationSequenceLength)
                )
                .Run()
                .SelectMany(a => a.Set)
                .ToArray();
            
            GC.Collect(); // To make it uniform w/ Go test

            _isInitialized = true;
        }

See More Examples