0
点赞
收藏
分享

微信扫一扫

弱鸡2,C# 一个List里面都是timer,如果list被clear,timer事件还会执行吗?


原来是不清楚的,不知道list clear之后还会不会执行事件。

其实是会的,因为这个timer对象还是在内存中的,只是clear被移除了引用。

原猜测是不是垃圾回收之后就会没有。,但实际上执行垃圾回收也没用。

不知道.net里面是不是timer不能被回收(因为有事件一直在等待或执行啊,所以不会被回收,因此GC.Collect()也没用?)

有大侠知道的话请指点。


using System;
using System.Collections.Generic;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;

namespace ConsoleApplication1
{
class Program
{
static List<Timer> timerList = new List<Timer>() { };

static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Timer timer = new Timer(5000)
{
Enabled = true
};
timer.Elapsed += Print;
timerList.Add(timer);
timer.Start();
}


Thread thread = new Thread(NewThread);
thread.Start();
Console.Read();

}


private static void NewThread()
{
Console.WriteLine("进入线程,开始睡15S" + DateTime.Now.ToLocalTime());
Thread.Sleep(14000);
Console.WriteLine("14S 之后,clear timers,注意看timers还执行吗" + DateTime.Now.ToLocalTime());
//timerList.Clear();
// GC.Collect();

timerList.ForEach(t=>t.Stop());
}

private static void Print(object sender, ElapsedEventArgs e)
{
Console.WriteLine(DateTime.Now.ToLocalTime());
}
}
}



举报

相关推荐

0 条评论