Add setTimeout and setinterval functions to C #

Source: Internet
Author: User

Call example:

Execution result:

2.

ImplementationCode:

Copy code The Code is as follows: // <summary>
2 // execute the specified expression after the specified time
3 /// </Summary>
4 /// <Param name = "interval"> time elapsed between events (in milliseconds) </param>
5 /// <Param name = "action"> expression to be executed </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 // execute the specified expression repeatedly in the specified time period
18 /// </Summary>
19 /// <Param name = "interval"> time elapsed between events (in milliseconds) </param>
20 /// <Param name = "action"> expression to be executed </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.

Because system. timers. timer is "server-based timer is designed for auxiliary threads in a multi-threaded Environment". Therefore, you should pay attention to it if you want to modify the UI object during use in winform, here is an example used in winform:

Running effect:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.