怎样让Timer的事件停止

  • 2026-08-06 02:44:08

using System;using System.Collections.Generic;using System.Text;using System.Timers;namespace eventTimer{ class Program { static int counter = 0; static string displayString = "This string will appear one letter at a time."; static int y=0; static void Main(string[] args) { Timer myTimer = new Timer(100); myTimer .Elapsed +=new ElapsedEventHandler(WriteChar); myTimer.Start(); Console.ReadKey(); } static void WriteChar(object source, ElapsedEventArgs e) { y=counter ++%displayString .Length; Console.Write(displayString[y]); } }}

看timer类的实现,可以用stop方法,或者设置enabled属性来控制但都不成功,必须要用console.readkey()来停止吗? 实现后的代码

1using System; 2using System.Collections.Generic; 3using System.Text; 4using System.Timers; 5 6namespace eventTimer 7{ 8 class Program 9 {10 static int counter = 0;11 static string displayString = "This string will appear one letter at a time.";12 static int y=0;13 1415 static void Main(string[] args)16 {17 Timer myTimer = new Timer(100); 18 myTimer .Elapsed +=new ElapsedEventHandler(WriteChar); 19 myTimer.Start(); 20 Console.ReadKey();21 }22 static void WriteChar(object source, ElapsedEventArgs e)23 {24 y=counter ++%displayString .Length;//y在这里表是字符数组的下标,所以y永远比length的值小1,假如length是50,而y的值范围是0——4925 if (y ==(displayString .Length -1))//注意这里要使用y==displayString.length-1.26 {27 Timer yy = (Timer)source;28 //yy.Enabled = false;29 yy.Stop();30 }31 else32 {33 Console.Write(displayString[y]);34 }35 36 373839 }40 }41}

还有一种终止的方法

using System;using System.Collections.Generic;using System.Text;using System.Timers;namespace eventTimer{ class Program { static int counter = 0; static string displayString = "This string will appear one letter at a time."; static int y=0; static DateTime newTime = System.DateTime.Now.AddSeconds(1); static void Main(string[] args) { Timer myTimer = new Timer(100); myTimer .Elapsed +=new ElapsedEventHandler(WriteChar); myTimer.Start(); Console.ReadKey(); } static void WriteChar(object source, ElapsedEventArgs e)//object source 表示引发事件对象的引用,ElapsedEventArgs e由事件传送的参数 { y=counter ++%displayString .Length;//y在这里表是字符数组的下标,所以y永远比length的值小1,假如length是50,而y的值范围是0——49 if (e.SignalTime >newTime )//注意这里要使用y==displayString.length-1. { Timer yang = (Timer)source;//这个是不是很熟悉呢? //yang.Enabled = false; Console.Write(displayString[y]);//这句是为了将最后一个字符输出 yang.Stop(); } //if (y == (displayString.Length - 1))//注意这里要使用y==displayString.length-1. //{ // Timer yang = (Timer)source;//这个是不是很熟悉呢? // //yang.Enabled = false; // Console.Write(displayString[y]);//这句是为了将最后一个字符输出 // yang.Stop(); //} else { Console.Write(displayString[y]); } } }}