码迷,mamicode.com
首页 > Windows程序 > 详细

C# has three timers

时间:2015-11-04 17:24:26      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

结论 *1.窗体timer和线程timer、计时器timer不同,因为后两者dispose之后,GC可以收集,而前者无法收集 *2.如果一个对象的成员函数正在被执行,那么这个对象肯定不会被收集 *3.要想对无引用的对象进行收集,就必须要终止这个对象的一切timer成员,否则无法收集该对象(因为timer正在使用该对象)。如果不停止timer就直接更改指针(这个对象彻底无法访问了),这就是新时代的内存泄露,程序早晚要内存溢出 *4.timer.stop 和timer.dispose 都会使线程终止,从而可以回收垃圾 */

 1 using System; 
 2 class TimersTimer
 3 { 
 4     System.Timers.Timer t;  
 5     public TimersTimer()
 6     {
 7         Console.WriteLine("Timers.Timer is created");
 8         t = new System.Timers.Timer();
 9         t.Interval = 1;
10         t.Elapsed += tick;
11         t.Start();
12     }
13     void tick(object o,EventArgs e )
14     {
15         t.Stop();
16         Console.WriteLine("tick is called");
17     }
18     ~TimersTimer()
19     {
20         Console.WriteLine("Timers.Timer is died");
21     }
22 }
23 class FormTimer
24 {
25     System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
26     public FormTimer()
27     {
28         Console.WriteLine("Form.Timer is called");
29         t.Interval = 1;
30         t.Tick += tick;
31         t.Start();
32     }
33     void tick(object o, EventArgs e)
34     {
35         Console.WriteLine("tick is called");
36         t.Dispose();
37     }
38     ~FormTimer()
39     {
40         Console.WriteLine("Form.Timer is deleted");
41     }
42 }
43 class ThreadTimer
44 {
45     System.Threading.Timer t;
46     public ThreadTimer()
47     {
48         Console.WriteLine("thread.timer is called");
49         t = new System.Threading.Timer(new System.Threading.TimerCallback(tick), null, 0, 1);
50     }
51     void tick(object o)
52     {
53         Console.WriteLine("tick is called");
54         t.Dispose();
55     }
56     ~ThreadTimer()
57     {
58         Console.WriteLine("thread.timer is died");
59     }
60 }
61 class haha
62 {
63     static void Main()
64     {
65         new TimersTimer();
66         System.Threading.Thread.Sleep(100);
67         GC.Collect();
68         System.Windows.Forms.Application.Run();
69     }
70 }
71 /*
72  * 结论
73  *1.窗体timer和线程timer、计时器timer不同,因为后两者dispose之后,GC可以收集,而前者无法收集
74  *2.如果一个对象的成员函数正在被执行,那么这个对象肯定不会被收集
75  *3.要想对无引用的对象进行收集,就必须要终止这个对象的一切timer成员,否则无法收集该对象(因为timer正在使用该对象)。如果不停止timer就直接更改指针(这个对象彻底无法访问了),这就是新时代的内存泄露,程序早晚要内存溢出
76  *4.timer.stop 和timer.dispose 都会使线程终止,从而可以回收垃圾
77 */

 

C# has three timers

标签:

原文地址:http://www.cnblogs.com/weidiao/p/4936444.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!