Sup*_*est 8 garbage-collection stopwatch c#-4.0
请考虑以下方法:
DoTimeIntensiveOperation()
{
var t = new Stopwatch();
foreach(var element in a_very_long_array)
{
DoATimeConsumingTask(element);
}
Console.WriteLine("Took me " + t.Elapsed);
return;
}
Run Code Online (Sandbox Code Playgroud)
t.Stop()回来之前我需要打电话吗?
据我所知,垃圾收集器会破坏任何没有引用链返回main方法的东西.对创建的唯一引用Stopwatch是t,所以何时DoTimeIntensiveOperation,t将被释放并且Stopwatch应该有资格进行销毁.但它仍在"滴答作响"的事实是否会干扰GC?
不,我扔了这个快速测试,似乎一旦GC运行,秒表就会被摧毁.(随意更正代码)
static void Main(string[] args)
{
DoTimeIntensiveOperation();
GC.Collect();
while (swRef.IsAlive)
{
}
Console.WriteLine("Destroyed");
}
static WeakReference swRef = null;
static void DoTimeIntensiveOperation()
{
Stopwatch sw = new Stopwatch();
sw.Start();
swRef = new WeakReference(sw);
return;
}
Run Code Online (Sandbox Code Playgroud)
输出是Destroyed在何时GC.Collect被调用.当然,在一个真实的程序中,你不太可能明确地调用,GC.Collect但这表明即使Stop没有调用,Stopwatch对象也会在方法范围之外被销毁.