c# – C #. Windows Service. Memory leaks

Question:

Please tell me where I made a mistake that the service is gradually eating up memory

The task of the service at startup is to load the addresses line by line from the Services.txt file into the List<Uri> and, at a certain interval, make a GET request for each URL from the file

Program.cs

static class Program
{
    static void Main()
    {
        ServiceBase[] ServicesToRun = {
            new ServicePusher()
        };

        ServiceBase.Run(ServicesToRun);
    }
}

ServicePusher.cs

public partial class ServicePusher : ServiceBase
{
    private static readonly Logger Log = LogManager.GetCurrentClassLogger();
    private Timer ServiceTimer;
    private readonly List<Uri> ServiceUrl = new List<Uri>();

    public ServicePusher()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/Services.txt"))
        {
            Log.Error("Не найден Services.txt");
            throw new FileNotFoundException("Не найден Services.txt");
        }

        using (StreamReader sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "/Services.txt"))
        {
            string line;

            while ((line = sr.ReadLine()) != null)
            {
                Uri serviceUri = null;

                try
                {
                    serviceUri = new Uri(line);
                }
                catch (Exception ex)
                {
                    Log.Error($"Ошибка при получении адреса сервиса ({line}): {ex}");
                }

                if (serviceUri != null)
                {
                    ServiceUrl.Add(serviceUri);
                }
                else
                {
                    Log.Error($"Некорректный адрес сервиса ({line}) в файле Services.txt");
                }
            }
        }

        ServiceTimer = new Timer
        {
            Interval = Config.Interval
        };

        ServiceTimer.Elapsed += Tick;
        ServiceTimer.AutoReset = true;
        ServiceTimer.Start();


        Log.Info("Сервис успешно запущен");
        Log.Info($"Загружено сервисов: {ServiceUrl.Count}");
    }

    protected override void OnStop()
    {
        ServiceTimer.Stop();
        ServiceTimer.Dispose();
        ServiceTimer = null;

        Log.Info("Сервис остановлен");
    }

    private void Tick(object sender, ElapsedEventArgs e)
    {
        try
        {
            foreach (Uri url in ServiceUrl)
            {
                ServicePointManager.ServerCertificateValidationCallback = (o, a, b, c) => true;

                WebRequest request = WebRequest.Create(url);
                request.Proxy = null;
                request.Method = "GET";
                request.Timeout = 360000;
                request.ContentType = "application/x-www-form-urlencoded";

                try
                {
                    using (WebResponse response = request.GetResponse())
                    {
                        using (Stream requestStream = response.GetResponseStream())
                        {
                            if (requestStream == null)
                            {
                                Log.Error($"Нет ответа от {url}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error($"Ошибка ({ex.Message}) при запросе к сервису {url}");
                }
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message);
        }
    }
}

UPD: eats up about 2 mb per hour

UPD 2: updated the code in the question, in 15 minutes it steadily eats ~ 350 kb …

Maybe it's Program.cs ?

Answer:

In general, my fears were in vain, I left the service to work all night, now it works and uses only 5 MB of memory

But it remains unclear why, when the service starts at first, it consumes about 11 MB

Scroll to Top