c# - Main 方法的垃圾收集(无限循环)

标签 c# asp.net garbage-collection

我正在实现一项无限期任务,该任务经常通过 .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/

相关文章:

c# - TimeSpan.ToString() 上的 System.FormatException

asp.net - 完成方法后面的代码后执行javascript方法?

javascript - Bootstrap 3 不会在手机或平板电脑尺寸上折叠导航栏

java - 为什么必须在 Eden 空间中创建新的 Java 对象?

c# - CLR 垃圾回收方法是否意味着可以安全地抛出循环对象引用?

c# - 如何查看当前操作系统是win8还是blue

c# - 将 Collection<Derived> 转换为 Collection<Base>

c# - 使用 moq 和 nunit 在 Action 结果 C# 中模拟类的方法

c# - 如何从pdf图像中查找文本?

脚本运行时的 php 垃圾回收