相关疑难解决方法(0)

为什么System.Timers.Timer能够在GC中存活但不能在System.Threading.Timer中存活?

似乎System.Timers.Timer实例通过某种机制保持活跃,但System.Threading.Timer实例却没有.

示例程序,具有定期System.Threading.Timer和自动重置功能System.Timers.Timer:

class Program
{
  static void Main(string[] args)
  {
    var timer1 = new System.Threading.Timer(
      _ => Console.WriteLine("Stayin alive (1)..."),
      null,
      0,
      400);

    var timer2 = new System.Timers.Timer
    {
      Interval = 400,
      AutoReset = true
    };
    timer2.Elapsed += (_, __) => Console.WriteLine("Stayin alive (2)...");
    timer2.Enabled = true;

    System.Threading.Thread.Sleep(2000);

    Console.WriteLine("Invoking GC.Collect...");
    GC.Collect();

    Console.ReadKey();
  }
}
Run Code Online (Sandbox Code Playgroud)

当我运行这个程序(.NET 4.0 Client,Release,在调试器之外)时,只有System.Threading.TimerGC是:

Stayin alive (1)...
Stayin alive (1)...
Stayin alive (2)...
Stayin alive (1)...
Stayin …
Run Code Online (Sandbox Code Playgroud)

.net garbage-collection timer

71
推荐指数
2
解决办法
1万
查看次数

标签 统计

.net ×1

garbage-collection ×1

timer ×1