Created
April 6, 2020 20:15
-
-
Save milovidov983/6481e4d23354d0b893ab79440968a5b3 to your computer and use it in GitHub Desktop.
Так выглядит отчаяние
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using LoggerWrapper; | |
| using System; | |
| using System.Diagnostics; | |
| namespace Exports.Service { | |
| /// <summary> | |
| /// Так как сервис жрёт память как не в себя, | |
| /// было принято временное решение реализовать сборку мусора в автоматическом режиме. | |
| /// </summary> | |
| public class ScavengerService { | |
| public static readonly ScavengerService Instance; | |
| public DateTime LastCollected; | |
| private const long MAX_MEM_LIMIT_MB = 900; | |
| private const long MAX_COLLECT_INTERVAL_MINUTES = 60; | |
| private readonly TimeSpan maxInterval = TimeSpan.FromMinutes(MAX_COLLECT_INTERVAL_MINUTES); | |
| private readonly ILogger logger = Settings.Logger; | |
| static ScavengerService() { | |
| Instance = new ScavengerService { | |
| LastCollected = DateTime.UtcNow | |
| }; | |
| } | |
| public void StartGarbageCollectionIfNecessary() { | |
| var currentAllocatedMemory = GetCurrentAllocatedMemoryMB(); | |
| logger.Info($"{nameof(ScavengerService)} Current allocated memory {currentAllocatedMemory} Mb"); | |
| if (currentAllocatedMemory >= MAX_MEM_LIMIT_MB) { | |
| ForceRunGarbageCollector(); | |
| } else if ((Instance.LastCollected + maxInterval) < DateTime.UtcNow) { | |
| ForceRunGarbageCollector(); | |
| } else { | |
| // do nothing | |
| } | |
| } | |
| private void ForceRunGarbageCollector() { | |
| logger.Info($"{nameof(ScavengerService)} Force run garbage collector"); | |
| var timer = new Stopwatch(); | |
| timer.Start(); | |
| /// https://stackoverflow.com/a/4257387/8840033 | |
| GC.Collect(); | |
| GC.WaitForPendingFinalizers(); | |
| Instance.LastCollected = DateTime.UtcNow; | |
| timer.Stop(); | |
| logger.Info($"{nameof(ScavengerService)} garbage collected in {timer.Elapsed.TotalSeconds} seconds"); | |
| } | |
| private long GetCurrentAllocatedMemoryMB() { | |
| /// https://stackoverflow.com/a/45503285/8840033 | |
| var proc = Process.GetCurrentProcess(); | |
| return proc.WorkingSet64 / 1048576; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment