【发布时间】:2014-04-19 08:25:16
【问题描述】:
我有一个 Windows 服务,它会定期检查数据库中的新记录并在新线程中处理每条记录(最多可能需要 10 分钟)。当服务在启动后立即空闲时,它需要 4 MB 的 RAM。当它开始处理第一条记录时,它会上升到 70+ MB 并且即使在线程完成后也保持在那里(我想这没关系,因为很快就会再次需要这个内存)。然后在下一个请求中,它会从 70 MB 增加到大约 100 MB,并且在线程完成后也停留在那里。 所以我的问题是这样的事情是否存在内存泄漏:
public partial class MyWinService : ServiceBase
{
DBService service;
IEnumerable<long> unfinishedRequests;
List<long> activeRequests;
protected override void OnStart(string[] args)
{
System.Timers.Timer timer1 = new System.Timers.Timer(60000);
timer1.Elapsed += Timer_Tick;
timer1.Start();
service = new DBService();
activeRequests = new List<long>();
}
private void Timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
unfinishedRequests = service.GetUnfinishedRequests();
foreach (var req in unfinishedRequests)
{
new Thread(delegate() { ProcessRequest(req); }).Start();
}
}
private void ProcessRequest(long requestID)
{
activeRequests.Add(requestID);
// Lots of webservice calls, XML->XSLT->HTML->PDF, byte arrays, database INSERTs & UPDATEs etc.
activeRequests.Remove(requestID);
}
}
ProcessRequest() 方法中创建的所有对象不应该在线程完成后销毁吗?如果程序在第一个线程之后已经有 100 MB 内存,为什么还要要求更多(在我的测试中,输入数据是相同的,所以我认为两个线程应该使用相同数量的内存)。
【问题讨论】:
标签: c# .net multithreading memory-leaks windows-services