请告诉我我在哪里犯了错误,该服务正在逐渐消耗内存
该服务在启动时的任务是逐行加载 Services.txt 文件中的地址,List<Uri>
并在一定时间间隔后对文件中的每个 URL 发出 GET 请求
程序.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:每小时消耗约 2 MB
UPD 2:更新问题中的代码,15分钟稳吃~350 kb ...
也许它在Program.cs中?
总的来说,我的担心是徒劳的,我让服务运行了一整夜,现在它可以运行并且只使用 5 MB 内存
但尚不清楚为什么在启动该服务时,它第一次消耗大约 11 MB。