我有以下代码:
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 将收集处置的(孤立的)对象并将它们设置为空?!
最佳答案
为什么您希望将其设置为 null
? using
/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/