C#--使用Timer类和Join方法管理线程

Timer类允许将"fire-and-forget"线程添加到用户程序。在实例化Timer对象时,需要指定以下4个参数

  • callback  提供Timer将调用方法的TimerCallback委托
  • state  应该传递给TimerCallback方法的对象。这个参数可为null
  • dueTime  Timer首次激发之前延迟的毫秒数
  • Period  Timer调用之间的毫秒数。

以下为Timer的一个示例:


1 /*
2 Example14_5.cs illustrates the use of the Timer class
3  */
4
5  using System;
6  using System.Threading;
7
8 class Example14_5
9 {
10
11 // the CheckTime method is called by the Timer
12 public static void CheckTime(Object state)
13 {
14 Console.WriteLine(DateTime.Now);
15 }
16
17 public static void Main()
18 {
19
20 // create the delegate that the Timer will call
21 TimerCallback tc = new TimerCallback(CheckTime);
22
23 // create a Timer that runs twice a second, starting in one second
24 Timer t = new Timer(tc, null, 1000, 500);
25
26 // Wait for user input
27 Console.WriteLine("Press Enter to exit");
28 int i = Console.Read();
29
30 // clean up the resources
31 t.Dispose();
32 t = null;
33
34 }
35
36 }

Thread.Join方法允许“持有” 某个线程,直至另一个线程完成其工作。如:


1 /*
2 Example14_6.cs shows the Thread.Join method in action
3 */
4
5 using System;
6 using System.Threading;
7
8 class Example14_6
9 {
10
11 // the Countdown method counts down from 1000 to 1
12 public static void Countdown()
13 {
14 for (int counter = 1000; counter > 0; counter--)
15 {
16 Console.Write(counter.ToString() + " ");
17 }
18 }
19
20 public static void Main()
21 {
22
23 // create a second thread
24 Thread t2 = new Thread(new ThreadStart(Countdown));
25
26 // launch the second thread
27 t2.Start();
28
29 // block the first thread until the second is done
30 t2.Join();
31
32 // and call the Countdown method from the first thread
33 Countdown();
34
35 }
36
37 }
上一篇:Ubuntu16.04设置屏幕分辨率


下一篇:为什么说systemd是系统管理员的利器