前天有个游戏里的变量是这样变化的,3-5分钟增加4-6次,再3-5分钟下降5-15次,然后使其变为0.我想了想,觉得改用定时器。于是就参考MSDN。搜索“Timer”。MSDN里关于Timer有四个。System.Windows.Forms.Timer,DispatcherTimer,System.Timers.Timer,System.Threading.Timer。我用WPF做过一些动画。于是立即用DispatcherTimer开始写了。测试一下发现,Tick似乎永远不执行。又试验了一下System.Windows.Forms.Timer。结果仍然是不执行start().MSDN中给出的例子是start后,由Application.DoEvents(); 才有效。我怕将来队列里事件多的话出错,就把这个舍弃了。于是不想再做。开始在博客园和MSDN论坛发帖求救。过来一天,回帖者寥寥,而且没有多少作用。为了不耽误时间,只好自己又认真看看MSDN,自己写吧。静下心后,很快就试验成功。System.Windows.Forms.Timer和DispatcherTimer计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用(MSDN)。 经过试验,只有System.Timers.Timer或者System.Threading.Timer这两个计时器可以。我最终用的后者。代码如下:
代码
 1 public static int count = 0;
 2 public static int total=0;
 3 public static Timer timer1;
 4 public static Timer timer2;
 5 public static Random ranobj;
 6 public static int timevalue;
 7 public static int a;
 8 public static int A = 0;
 9 public static void Main()
10 {
11 ranobj = new Random();
12 
13 = ranobj.Next(35);
14 total = ranobj.Next(46);
15 timevalue = (a * 60/ total;
16 timer1 = new Timer(new TimerCallback(CheckStatus), null0, timevalue * 1000);
17 
18 Console.ReadLine();
19 }
20 
21 
22 static void CheckStatus(Object state)
23 {
24 
25 if (count < total)
26 {
27 count++;
28 A++;
29 
30 }
31 else
32 {
33 count = 0;
34 timer1.Dispose();
35 total = ranobj.Next(515);
36 timevalue = (a * 60/ total;
37 timer2 = new Timer(new TimerCallback(CheckStatus2), null0, timevalue * 1000);
38 }
39 
40 }
41 
42 static void CheckStatus2(Object state)
43 {
44 
45 if (count < total)
46 {
47 count++;
48 A--;
49 
50 }
51 else
52 {
53 count = 0;
54 timer2.Dispose();
55 }
56 
57 }


这个计时器的代码很简单,我却花了两天时间,只能说明很浮躁。遇到问题为什么就不能认真想想,总想得到现成的答案呢?我发现上学上到现在,时候有时候总养成了被填鸭的习惯。百度一下,你就知道,在深入人心的时候,也破坏了我们的一些独自思考的能力。以后遇到类似的事情,一定要冷静分析,尽量自己解决。实在解决不了,再百度吧。
posted on 2010-06-28 22:19  newhi  阅读(2141)  评论(8编辑  收藏  举报