参照文档:https://docs.microsoft.com/zh-cn/dotnet/api/system.timers.timer?view=netframework-4.8
static void Main(string[] args) { Console.WriteLine(DateTime.Now.ToString()); SetTimeOut(2000, alert, "你好"); Thread.Sleep(20000); Console.Read(); } /// <summary> /// 延迟处理 /// </summary> /// <param name="interval">延时时间:毫秒</param> /// <param name="action">调用方法</param> /// <param name="hello">方法入参</param> static void SetTimeOut(double interval,Action<string> action,string hello) { System.Timers.Timer timer = new System.Timers.Timer(); timer.AutoReset = false;//是否只触发一次 timer.Interval = interval;//时间间隔 //绑定匿名方法 timer.Elapsed += delegate (object sender, System.Timers.ElapsedEventArgs e) { timer.Enabled = false;//停用触发 action(hello); }; timer.Enabled = true;//启用触发 } static void alert(string s) { Console.WriteLine($"{DateTime.Now.ToString()}--{s}"); }
以上信息仅用于学习交流,如有错误欢迎指正;大佬勿喷,谢谢;