我正在实现一项无限期任务,该任务经常通过 .net 控制台应用程序运行。但是我担心下面会导致内存泄漏。由于 Main 是静态的(这是我对垃圾收集的了解变得模糊的地方),这是否意味着我在 try 和 catch 中创建的对象在 Main 完成(永远不会)之前不会被垃圾收集器拾取?
有人可以解释垃圾收集器在这种情况下的行为吗?
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile("Logs/log-{Date}.txt")
.CreateLogger();
while (true)
{
try
{
Thread.Sleep(1000);
new UpdatePlayer().Run();
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
}
}
最佳答案
您不会有内存泄漏:Main
没有 任何对 UpdatePlayer()
的引用实例:
...
try
{
Thread.Sleep(1000);
// Instance created, executed
new UpdatePlayer().Run();
}
// And can be safely collected here when the instance is out of scope (`try {...}`)
// the anonymous instance can't be accessed and that's enough
有内存泄漏的示例:
// please notice, that anchor is outside the `while(true)` scope
List<Object> anchor = new List<Object>();
...
while (true)
{
try
{
Thread.Sleep(1000);
// Instance created
var item = new UpdatePlayer();
// anchored
anchor.Add(item);
// and executed
item.Run();
}
// item can't be collected here: anchor has a reference to it
// And the item potentially can be accessed by, say, anchor[0]
编辑:如果您将集合移动到while(true)
范围内,代码将没有内存泄漏:
try
{
List<object> pseudoAnchor = new List<object>();
// Instance created
var item = new UpdatePlayer();
// tried to be anchored (illusion)
pseudoAnchor.Add(item);
// and executed
item.Run();
}
...
// the only reference to item is pseudoAnchor, but
// pseudoAnchor has not been referenced, and so GC
// can safely collect entire pseudoAnchor with all its items
// (just one `item` in fact)
关于c# - Main 方法的垃圾收集(无限循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004852/