文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C#--理解线程

C#--理解线程

时间:2011-05-10  来源:孤独的猫

  •      一个进程可以有一个或多个线程,这些线程共享资源。CPU按照它自己的进度表,在各线程间切换。

     线程并不提高计算机在给定时间内可以完成的工作量,但可以使计算机相应更加灵活。在.Net中,用Thread类来创建线程。如:

 1 /*
2 Example14_1.cs illustrates the creation of threads
3 */
4
5 using System;
6 using System.Threading;
7
8 class Example14_1 {
9
10 // the Countdown method counts down from 1000 to 1
11 public static void Countdown() {
12 for (int counter = 1000; counter > 0; counter--) {
13 Console.Write(counter.ToString() + " ");
14 }
15 }
16
17 public static void Main() {
18
19 // create a second thread
20 Thread t2 = new Thread(new ThreadStart(Countdown));
21
22 // launch the second thread
23 t2.Start();
24
25 // and meanwhile call the Countdown method from the first thread
26 Countdown();
27
28 }
29
30 }

设置优先级

Thread对象可以定义5个优先级:

  • Lowest
  • BelowNormal
  • Normal
  • AboveNormal
  • Highest

 用属性Priority类设置:

 1 /*
2 Example14_2.cs illustrates the use of thread priorities
3 */
4
5 using System;
6 using System.Threading;
7
8 class Example14_2
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 // set the new thread to highest priority
27 t2.Priority=ThreadPriority.Highest;
28
29 // Locate the current thread and set it to the lowest priority
30 Thread.CurrentThread.Priority=ThreadPriority.Lowest;
31
32 // launch the second thread
33 t2.Start();
34
35 // and meanwhile call the Countdown method from the first thread
36 Countdown();
37
38 }
39
40 }
相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载