给c#添加SetTimeout和SetInterval函数
时间:2021-07-02 00:58:08
调用示例:
执行效果:
2.
实现代码:
/// <summary>
2 /// 在指定时间过后执行指定的表达式
3 /// </summary>
4 /// <param name="interval">事件之间经过的时间(以毫秒为单位)</param>
5 /// <param name="action">要执行的表达式</param>
6 public static void SetTimeout(double interval, Action action)
7 {
8 System.Timers.Timer timer = new System.Timers.Timer(interval);
9 timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
10 {
11 timer.Enabled = false;
12 action();
13 };
14 timer.Enabled = true;
15 }
16 /// <summary>
17 /// 在指定时间周期重复执行指定的表达式
18 /// </summary>
19 /// <param name="interval">事件之间经过的时间(以毫秒为单位)</param>
20 /// <param name="action">要执行的表达式</param>
21 public static void SetInterval(double interval, Action<ElapsedEventArgs> action)
22 {
23 System.Timers.Timer timer = new System.Timers.Timer(interval);
24 timer.Elapsed += delegate(object sender, System.Timers.ElapsedEventArgs e)
25 {
26 action(e);
27 };
28 timer.Enabled = true;
29 }
3.
由于System.Timers.Timer 是“基于服务器的 Timer 是为在多线程环境中用于辅助线程而设计的”,所以在winform中使用时如果要修改UI对象就要注意了,给个在winform中使用的例子:
运行效果:
标签:c#,SetTimeout,SetInterval
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Java Proxy动态 代理机制
2023-07-24 21:01:58
![](https://img.aspxhome.com/file/2023/6/57726_0s.png)
Java数据结构之图的路径查找算法详解
2023-03-27 03:47:11
![](https://img.aspxhome.com/file/2023/6/67996_0s.png)
Java实战入门之双色球彩票小游戏
2023-05-12 04:07:13
![](https://img.aspxhome.com/file/2023/6/63486_0s.png)
Java语法中Lambda表达式无法抛出异常的解决
2022-10-13 01:04:43
Java 中很好用的数据结构EnumSet
2023-12-06 09:37:23
![](https://img.aspxhome.com/file/2023/5/64395_0s.webp)
java实现操作系统中的最佳置换Optimal算法
2023-10-26 10:27:13
![](https://img.aspxhome.com/file/2023/0/76630_0s.jpg)
解析JAVA深度克隆与浅度克隆的区别详解
2023-11-02 10:57:28
java 创建线程的几种方式
2023-10-29 19:40:16
![](https://img.aspxhome.com/file/2023/5/58695_0s.png)
Java中lombok的@Builder注解的解析与简单使用详解
2022-12-29 06:44:55
java转树形结构工具类详解
2021-07-26 04:00:08
JAVA如何调用Shell脚本
2022-11-25 01:13:13
Winform 实现进度条弹窗和任务控制
2023-06-20 04:27:09
![](https://img.aspxhome.com/file/2023/4/66134_0s.png)
Java实现窗体程序显示日历
2022-09-14 11:01:59
![](https://img.aspxhome.com/file/2023/4/72534_0s.jpg)
DecimalFormat多种用法详解
2022-11-13 15:06:52
Java中实现双数组Trie树实例
2023-03-19 15:12:38
MyBatis使用动态SQL标签的小陷阱
2023-09-11 04:42:57
java开源调度如何给xxljob加k8s执行器
2021-09-17 16:41:50
![](https://img.aspxhome.com/file/2023/9/62229_0s.png)
详解C#对XML、JSON等格式的解析
2022-06-04 22:45:50
![](https://img.aspxhome.com/file/2023/5/68615_0s.jpg)
详解Java利用深度优先遍历解决迷宫问题
2022-08-20 02:46:54
Springboot如何根据实体类生成数据库表
2023-11-20 13:54:39
![](https://img.aspxhome.com/file/2023/7/59677_0s.jpg)