c# - 编译器是否将处置的对象设置为空?

标签 c# .net garbage-collection

我有以下代码:

public class Program
{
 private static Task task;
 private static int counter = 0;

 private static void Main(string[] args)
 {
   for (int i = 0; i < 10; i++)
   {
    if (task == null)
    {
      Console.WriteLine(++counter);
    }

     using (task = new Task(Method))
     {
       task.Start();
       task.Wait();
     }

     //  task = null;

     GC.Collect();
     GC.WaitForPendingFinalizers();
   } 

   Console.ReadKey();
 }

 public static void Method() { }
 }

我的异常(exception)输出:1 2 3 4 5 6...但是这个方法的实际输出是 1!

如果我从代码行 Task = null; 中删除注释,那么我将成为预期的结果。

为什么处理的任务不为空!?我想,如果对象被处置,那么它们可以从 GC 中设置为空(我已经强制 GC 收集)换句话说,GC 将收集处置的(孤立的)对象并将它们设置为空?!

最佳答案

为什么您希望将其设置为 nullusing/Dispose() 从未说过它会那样做。它 promise 处理它。这里的最佳做法是在 using 语句中使用单独的变量以避免混淆:

using(var t = new Task(Method))
{
    t.Start();
    t.Wait();
}

但是如果你想让它设置为null; 将其设置为空:

task = null;

关于你的另一点:

in other words the GC will collect the disposed(orphan) objects and put them to null?!

GC 也从不将任何内容设置为 null;它收集无法访问的东西:仅此而已

关于c# - 编译器是否将处置的对象设置为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20123817/

相关文章:

javascript - 从数据库加载时网页挂起,并且大数据未显示在 asp.net mvc5 的图表上

.net - 问题 : . NET 代码从同一磁盘上的一个目录而不是另一个目录运行

c++ - 为什么我只能在 Ubuntu 的 G++ 中获得垃圾值?

c# - 使用 C# HttpClient API 和 postman 测试的区别?客户端调用适用于 postman ,但不适用于 C# httpClient getAsync

c# - 在Linq查询中选择不重复

c# - 使用 LINQ 按类型合并序列

c# - AADSTS9002331 : Application is configured for use by Microsoft Account users only. 请使用/consumers 端点来满足此请求

c# - 不会等待从 UnhandledException 处理程序调用的异步方法

Java 堆术语 : young, 老代和永久代?

java - JVM 在旧代为 'empty' 时运行旧代垃圾回收