日期:2011-05-11  浏览次数:20374 次

Don't believe everything they've told you. Threads in C# are actually pretty easy.

 

别相信别人告诉你的所有的事。其实C#中的线程是很简单的。

 

A thread is an encapsulation of the flow of control in a program. you might be used to writing single-threaded programs - that is, programs that only execute one path through their code "at a time". If you have more than one thread, then code paths run "simultaneously".

 

线程是程序中的控制流程的封装。你可能已经习惯于写单线程程序,也就是,程序在它们的代码中一次只在一条路中执行。如果你多弄几个线程的话,代码运行可能会更加“同步”。

 

Why are some phrases above in quotes? In a typical process in which multiple threads exist, zero or more threads may actually be running at any one time. However on a machine that got n CPU's only one thread (actually) can run at any given time on each CPU, because each thread is a code path, each CPU can only run one code-action at a time. The appearance of running many more than n "simultaneously" is done by sharing the CPUs among threads.

 

在一个有着多线程的典型进程中,零个或更多线程在同时运行。但是,在有着N个CPU的机器上,一个线程只能在给定的时间上在一个CPU上运行,因为每个线程都是一个代码段,每个CPU一次只能运行一段代码。而看起来像是N个同时完成是线程间共享CPU时间片的效果。

 

In this example we will create another thread, we will try to implement a way to demonstrate the multithreaded way of working between the two threads we have, and at the end, we will sync the two threads (the main and the new one) for letting the new thread "wait" for a message before continuing.

 

这个例子里,我们将创建另一个线程,我们将用两个线程演示多线程的工作方式,最后,我们实现两个线程(主线程与新线程)同步,在新线程工作前必须等待消息。

 

To create a thread we need to add the System.Threading namespace. After that we need to understand that a thread has GOT to have a start point for its flow of control. The start point is a function, which should be in the same call or in a different one.

 

建立线程前我们必须引入System.Threading命名空间。然后我需要知道的是,线程得为控制流程建立一个起点。起点是一个函数,可以使一个相同的调用或其它。

 

Here you can see a function in the same class that is defined as the start point.

 

这里你可以看到在同一个类中定义的起点函数。

 

using System;

using System.Threading;

 

namespace ThreadingTester

{

 

 

 

 class ThreadClass

 {

 

   public static void trmain()

   {

   

    for(int x=0;x < 10;x++)

    {

     Thread.Sleep(1000);

     Console.WriteLine(x);

    }

   } 

 

 

   static void Main(string[] args)

   {