前天有个游戏里的变量是这样变化的,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 a = ranobj.Next(3, 5);
14 total = ranobj.Next(4, 6);
15 timevalue = (a * 60) / total;
16 timer1 = new Timer(new TimerCallback(CheckStatus), null, 0, 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(5, 15);
36 timevalue = (a * 60) / total;
37 timer2 = new Timer(new TimerCallback(CheckStatus2), null, 0, 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 }
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 a = ranobj.Next(3, 5);
14 total = ranobj.Next(4, 6);
15 timevalue = (a * 60) / total;
16 timer1 = new Timer(new TimerCallback(CheckStatus), null, 0, 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(5, 15);
36 timevalue = (a * 60) / total;
37 timer2 = new Timer(new TimerCallback(CheckStatus2), null, 0, 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 }