see:
http://www.pconline.com.cn/pcedu/empolder/gj/vc/10305/168480.html
http://www.zdnet.com.cn/developer/tech/story/0,2000081602,39112543,00.htm
http://www.pconline.com.cn/pcedu/empolder/gj/vc/10305/168480.html
http://www.zdnet.com.cn/developer/tech/story/0,2000081602,39112543,00.htm
using System.Threading;// Simple threading scenario: Start a static method running
// on a second thread.
public class ThreadExample {
// The ThreadProc method is called when the thread starts.
// It loops ten times, writing to the console and yielding
// the rest of its time slice each time, and then ends.
public static void ThreadProc() {
for (int i = 0; i < 10; i++) {
Console.WriteLine("ThreadProc: {0}", i);
// Yield the rest of the time slice.
Thread.Sleep(0);
}
} public static void Main() {
Console.WriteLine("Main thread: Start a second thread.");
// The constructor for the Thread class requires a ThreadStart
// delegate that represents the method to be executed on the
// thread. C# simplifies the creation of this delegate.
Thread t = new Thread(new ThreadStart(ThreadProc));
// Start ThreadProc. On a uniprocessor, the thread does not get
// any processor time until the main thread yields. Uncomment
// the Thread.Sleep that follows t.Start() to see the difference.
t.Start();
//Thread.Sleep(0); for (int i = 0; i < 4; i++) {
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(0);
} Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
t.Join();
Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program.");
Console.ReadLine();
}
}
多线程是许多操作系统所具有的特性,它能大大提高程序的运行效率,所以多线程编程技术为编程者广泛关注。目前微软的.Net战略正进一步推进,各种相关的技术正为广大编程者所接受,同样在.Net中多线程编程技术具有相当重要的地位。本文我就向大家介绍在.Net下进行多线程编程的基本方法和步骤。
开始新线程
在.Net下创建一个新线程是非常容易的,你可以通过以下的语句来开始一个新的线程:
Thread thread = new Thread (new ThreadStart (ThreadFunc));
thread.Start ();
第一条语句创建一个新的Thread对象,并指明了一个该线程的方法。当新的线程开始时,该方法也就被调用执行了。该线程对象通过一个System..Threading.ThreadStart类的一个实例以类型安全的方法来调用它要调用的线程方法。
第二条语句正式开始该新线程,一旦方法Start()被调用,该线程就保持在一个"alive"的状态下了,你可以通过读取它的IsAlive属性来判断它是否处于"alive"状态。下面的语句显示了如果一个线程处于"alive"状态下就将该线程挂起的方法:
if (thread.IsAlive) {
thread.Suspend ();
}
不过请注意,线程对象的Start()方法只是启动了该线程,而并不保证其线程方法ThreadFunc()能立即得到执行。它只是保证该线程对象能被分配到CPU时间,而实际的执行还要由操作系统根据处理器时间来决定。
一个线程的方法不包含任何参数,同时也不返回任何值。它的命名规则和一般函数的命名规则相同。它既可以是静态的(static)也可以是非静态的(nonstatic)。当它执行完毕后,相应的线程也就结束了,其线程对象的IsAlive属性也就被置为false了。下面是一个线程方法的实例:
public static void ThreadFunc()
{
for (int i = 0; i <10; i++) {
Console.WriteLine("ThreadFunc {0}", i);
}
}
前台线程和后台线程
.Net的公用语言运行时(Common Language Runtime,CLR)能区分两种不同类型的线程:前台线程和后台线程。这两者的区别就是:应用程序必须运行完所有的前台线程才可以退出;而对于后台线程,应用程序则可以不考虑其是否已经运行完毕而直接退出,所有的后台线程在应用程序退出时都会自动结束。
一个线程是前台线程还是后台线程可由它的IsBackground属性来决定。这个属性是可读又可写的。它的默认值为false,即意味着一个线程默认为前台线程。我们可以将它的IsBackground属性设置为true,从而使之成为一个后台线程。
下面的例子是一个控制台程序,程序一开始便启动了10个线程,每个线程运行5秒钟时间。由于线程的IsBackground属性默认为false,即它们都是前台线程,所以尽管程序的主线程很快就运行结束了,但程序要到所有已启动的线程都运行完毕才会结束。示例代码如下:
using System;
using System.Threading;
class MyApp
{
public static void Main ()
{
for (int i=0; i<10; i++) {
Thread thread = new Thread (new ThreadStart (ThreadFunc));
thread.Start ();
}
}
private static void ThreadFunc ()
{
DateTime start = DateTime.Now;
while ((DateTime.Now - start).Seconds <5)
;
}
}
接下来我们对上面的代码进行略微修改,将每个线程的IsBackground属性都设置为true,则每个线程都是后台线程了。那么只要程序的主线程结束了,整个程序也就结束了。示例代码如下:
using System;
using System.Threading;
class MyApp
{
public static void Main ()
{
for (int i=0; i<10; i++) {
Thread thread = new Thread (new ThreadStart (ThreadFunc));
thread.IsBackground = true;
thread.Start ();
}
}
private static void ThreadFunc ()
{
DateTime start = DateTime.Now;
while ((DateTime.Now - start).Seconds <5)
;
}
}
既然前台线程和后台线程有这种差别,那么我们怎么知道该如何设置一个线程的IsBackground属性呢?下面是一些基本的原则:对于一些在后台运行的线程,当程序结束时这些线程没有必要继续运行了,那么这些线程就应该设置为后台线程。比如一个程序启动了一个进行大量运算的线程,可是只要程序一旦结束,那个线程就失去了继续存在的意义,那么那个线程就该是作为后台线程的。而对于一些服务于用户界面的线程往往是要设置为前台线程的,因为即使程序的主线程结束了,其他的用户界面的线程很可能要继续存在来显示相关的信息,所以不能立即终止它们。这里我只是给出了一些原则,具体到实际的运用往往需要编程者的进一步仔细斟酌。
线程优先级
一旦一个线程开始运行,线程调度程序就可以控制其所获得的CPU时间。如果一个托管的应用程序运行在Windows机器上,则线程调度程序是由Windows所提供的。在其他的平台上,线程调度程序可能是操作系统的一部分,也自然可能是.Net框架的一部分。不过我们这里不必考虑线程的调度程序是如何产生的,我们只要知道通过设置线程的优先级我们就可以使该线程获得不同的CPU时间。
线程的优先级是由Thread.Priority属性控制的,其值包含:ThreadPriority.Highest、ThreadPriority.AboveNormal、ThreadPriority.Normal、ThreadPriority.BelowNormal和ThreadPriority.Lowest。从它们的名称上我们自然可以知道它们的优先程度,所以这里就不多作介绍了。
线程的默认优先级为ThreadPriority.Normal。理论上,具有相同优先级的线程会获得相同的CPU时间,不过在实际执行时,消息队列中的线程阻塞或是操作系统的优先级的提高等原因会导致具有相同优先级的线程会获得不同的CPU时间。不过从总体上来考虑仍可以忽略这种差异。你可以通过以下的方法来改变一个线程的优先级。
thread.Priority = ThreadPriority.AboveNormal;
或是:
thread.Priority = ThreadPriority.BelowNormal;
通过上面的第一句语句你可以提高一个线程的优先级,那么该线程就会相应的获得更多的CPU时间;通过第二句语句你便降低了那个线程的优先级,于是它就会被分配到比原来少的CPU时间了。你可以在一个线程开始运行前或是在它的运行过程中的任何时候改变它的优先级。理论上你还可以任意的设置每个线程的优先级,不过一个优先级过高的线程往往会影响到其他线程的运行,甚至影响到其他程序的运行,所以最好不要随意的设置线程的优先级。
挂起线程和重新开始线程
Thread类分别提供了两个方法来挂起线程和重新开始线程,也就是Thread.Suspend能暂停一个正在运行的线程,而Thread.Resume又能让那个线程继续运行。不像Windows内核,.Net框架是不记录线程的挂起次数的,所以不管你挂起线程过几次,只要一次调用Thread.Resume就可以让挂起的线程重新开始运行。
Thread类还提供了一个静态的Thread.Sleep方法,它能使一个线程自动的挂起一定的时间,然后自动的重新开始。一个线程能在它自身内部调用Thread.Sleep方法,也能在自身内部调用Thread.Suspend方法,可是一定要别的线程来调用它的Thread.Resume方法才可以重新开始。这一点是不是很容易想通的啊?下面的例子显示了如何运用Thread.Sleep方法:
while (ContinueDrawing) {
DrawNextSlide ();
Thread.Sleep (5000);
}
终止线程
在托管的代码中,你可以通过以下的语句在一个线程中将另一个线程终止掉:
thread.Abort ();
下面我们来解释一下Abort()方法是如何工作的。因为公用语言运行时管理了所有的托管的线程,同样它能在每个线程内抛出异常。Abort()方法能在目标线程中抛出一个ThreadAbortException异常从而导致目标线程的终止。不过Abort()方法被调用后,目标线程可能并不是马上就终止了。因为只要目标线程正在调用非托管的代码而且还没有返回的话,该线程就不会立即终止。而如果目标线程在调用非托管的代码而且陷入了一个死循环的话,该目标线程就根本不会终止。不过这种情况只是一些特例,更多的情况是目标线程在调用托管的代码,一旦Abort()被调用那么该线程就立即终止了。
在实际应用中,一个线程终止了另一个线程,不过往往要等那个线程完全终止了它才可以继续运行,这样的话我们就应该用到它的Join()方法。示例代码如下:
thread.Abort (); // 要求终止另一个线程
thread.Join (); // 只到另一个线程完全终止了,它才继续运行
但是如果另一个线程一直不能终止的话(原因如前所述),我们就需要给Join()方法设置一个时间限制,方法如下:
thread.Join (5000); // 暂停5秒
这样,在5秒后,不管那个线程有没有完全终止,本线程就强行运行了。该方法还返回一个布尔型的值,如果是true则表明那个线程已经完全终止了,而如果是false的话,则表明已经超过了时间限制了。
.Net框架中的Timer类可以让你使用时钟线程,它是包含在System.Threading名字空间中的,它的作用就是在一定的时间间隔后调用一个线程的方法。下面我给大家展示一个具体的实例,该实例以1秒为时间间隔,在控制台中输出不同的字符串,代码如下:
using System;
using System.Threading;
class MyApp
{
private static bool TickNext = true;
public static void Main ()
{
Console.WriteLine ("Press Enter to terminate...");
TimerCallback callback = new TimerCallback (TickTock);
Timer timer = new Timer (callback, null, 1000, 1000);
Console.ReadLine ();
}
private static void TickTock (object state)
{
Console.WriteLine (TickNext ? "Tick" : "Tock");
TickNext = ! TickNext;
}
}
从上面的代码中,我们知道第一个函数回调是在1000毫秒后才发生的,以后的函数回调也是在每隔1000毫秒之后发生的,这是由Timer对象的构造函数中的第三个参数所决定的。程序会在1000毫秒的时间间隔后不断的产生新线程,只到用户输入回车才结束运行。不过值得注意的是,虽然我们设置了时间间隔为1000毫秒,但是实际运行的时候往往并不能非常精确。因为Windows操作系统并不是一个实时系统,而公用语言运行时也不是实时的,所以由于线程调度的千变万化,实际的运行效果往往是不能精确到毫秒级的,但是对于一般的应用来说那已经是足够的了,所以你也不必十分苛求。
{
// m_mutext很快可以得到,以便进入临界区
m_mutex.WaitOne( );
// 是否有写入线程存在
bool bExistingWriter = ( m_nActive < 0 );
if( bExistingWriter )
{ //等待阅读线程数目加1,当有锁释放时,根据此数目来调度线程
m_nWaitingReaders++;
}
else
{ //当前活动线程加1
m_nActive++;
}
m_mutex.ReleaseMutex();
//存储锁标志为Reader
System.LocalDataStoreSlot slot = Thread.GetNamedDataSlot(m_strThreadSlotName);
object obj = Thread.GetData( slot );
LockFlags flag = LockFlags.None;
if( obj != null )
flag = (LockFlags)obj ;
if( flag == LockFlags.None )
{
Thread.SetData( slot, LockFlags.Reader );
}
else
{
Thread.SetData( slot, (LockFlags)((int)flag | (int)LockFlags.Reader ) );
}
if( bExistingWriter )
{ //等待指定的时间
this.m_aeReaders.WaitOne( millisecondsTimeout, true );
}
}
public void ddr()
{
for (int i=0;i<10;i++)
{
Thread t=new Thread(new ThreadStart(ThreadProc));
t.Start();
}private void ThreadProc()
{
for (int i=0;i<10;i++)
{
double sumrnd=0.00;
Random rnd=new Random();
sumrnd+=rnd.NextDouble();
}
}如此一来,我如何才能获得ThreadProc中各个 sumrnd 的值呢?
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace AsynchCalcPi
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button _calcButton;
private System.Windows.Forms.NumericUpDown _digits;
private System.Windows.Forms.TextBox _pi;
private System.Windows.Forms.ProgressBar _piProgress;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Button btnShowThead;
private System.Windows.Forms.TextBox tbShowThread;
private System.Windows.Forms.Button btnShowPro; enum CalcState
{
Pending, // 没有任何计算正在运行或取消
Calculating, // 正在计算
Canceled, // 在 UI 中计算已被取消但在辅助线程中还没有
} CalcState _state = CalcState.Pending; // 没有任何计算正在运行或取消 public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent(); //
// TODO: Add any constructor code after InitializeComponent call
//
} /// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();//释放由 Component 占用的资源
}
}
base.Dispose( disposing );
} #region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this._calcButton = new System.Windows.Forms.Button();
this._digits = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this._pi = new System.Windows.Forms.TextBox();
this._piProgress = new System.Windows.Forms.ProgressBar();
this.btnShowThead = new System.Windows.Forms.Button();
this.tbShowThread = new System.Windows.Forms.TextBox();
this.btnShowPro = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this._digits)).BeginInit();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.AddRange(new System.Windows.Forms.Control[] {
this._calcButton,
this._digits,
this.label1});
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(504, 46);
this.panel1.TabIndex = 0;
//
// _calcButton
//
this._calcButton.Location = new System.Drawing.Point(200, 8);
this._calcButton.Name = "_calcButton";
this._calcButton.Size = new System.Drawing.Size(64, 27);
this._calcButton.TabIndex = 2;
this._calcButton.Text = "计算";
this._calcButton.Click += new System.EventHandler(this._calcButton_Click);
//
// _digits
//
this._digits.Location = new System.Drawing.Point(104, 8);
this._digits.Maximum = new System.Decimal(new int[] {
10000,
0,
0,
0});
this._digits.Name = "_digits";
this._digits.Size = new System.Drawing.Size(72, 21);
this._digits.TabIndex = 1;
//
// label1
//
this.label1.Location = new System.Drawing.Point(10, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(118, 27);
this.label1.TabIndex = 0;
this.label1.Text = "Pi的小数位数:";
//
// _pi
//
this._pi.Location = new System.Drawing.Point(0, 48);
this._pi.Multiline = true;
this._pi.Name = "_pi";
this._pi.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this._pi.Size = new System.Drawing.Size(504, 104);
this._pi.TabIndex = 1;
this._pi.Text = "3";
//
// _piProgress
//
this._piProgress.Dock = System.Windows.Forms.DockStyle.Bottom;
this._piProgress.Location = new System.Drawing.Point(0, 314);
this._piProgress.Maximum = 1;
this._piProgress.Name = "_piProgress";
this._piProgress.Size = new System.Drawing.Size(504, 27);
this._piProgress.TabIndex = 2;
//
// btnShowThead
//
this.btnShowThead.Location = new System.Drawing.Point(152, 160);
this.btnShowThead.Name = "btnShowThead";
this.btnShowThead.Size = new System.Drawing.Size(64, 24);
this.btnShowThead.TabIndex = 3;
this.btnShowThead.Text = "显示线程";
this.btnShowThead.Click += new System.EventHandler(this.btnShowThead_Click);
//
// tbShowThread
//
this.tbShowThread.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right);
this.tbShowThread.Location = new System.Drawing.Point(0, 192);
this.tbShowThread.Multiline = true;
this.tbShowThread.Name = "tbShowThread";
this.tbShowThread.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.tbShowThread.Size = new System.Drawing.Size(496, 120);
this.tbShowThread.TabIndex = 3;
this.tbShowThread.Text = "";
//
// btnShowPro
//
this.btnShowPro.Location = new System.Drawing.Point(56, 160);
this.btnShowPro.Name = "btnShowPro";
this.btnShowPro.Size = new System.Drawing.Size(64, 24);
this.btnShowPro.TabIndex = 4;
this.btnShowPro.Text = "显示进程";
this.btnShowPro.Click += new System.EventHandler(this.btnShowPro_Click);
//
// Form1
//
this.AcceptButton = this._calcButton;
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(504, 341);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnShowPro,
this.tbShowThread,
this._pi,
this.panel1,
this._piProgress,
this.btnShowThead});
this.Name = "Form1";
this.Text = "Digits of Pi";
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this._digits)).EndInit();
#endregion /// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
} delegate void ShowProgressDelegate(string pi, int totalDigits, int digitsSoFar, out bool cancel); void ShowProgress(string pi, int totalDigits, int digitsSoFar, out bool cancel)
{
//确保在正确的线程上
if( _pi.InvokeRequired == false )
{
_pi.Text = pi; //文本框
_piProgress.Maximum = totalDigits; //状态条
_piProgress.Value = digitsSoFar; // Check for Cancel // 检查是否取消
cancel = (_state == CalcState.Canceled); // Check for completion// 检查是否完成
if( cancel || (digitsSoFar == totalDigits) )
{
_state = CalcState.Pending;// 没有任何计算正在运行或取消
_calcButton.Text = "计算";
_calcButton.Enabled = true; }
}
// Transfer control to correct thread//转到正确的线程上
else
{
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
object inoutCancel = false; // 避免包装或丢失返回值// Avoid boxing and losing our return value // Show progress synchronously (so we can check for cancel)
// 同步显示进度(这样我们可以检查是否取消)
Invoke(showProgress, new object[] { pi, totalDigits, digitsSoFar, inoutCancel});
cancel = (bool)inoutCancel; // Show progress asynchronously//异步显示进度
//BeginInvoke(showProgress, new object[] { pi, totalDigits, digitsSoFar, inoutCancel});
}
} void CalcPi(int digits)
{
bool cancel = false;
StringBuilder pi = new StringBuilder("3", digits + 2); // Show progress (ignoring Cancel so soon)
ShowProgress(pi.ToString(), digits, 0, out cancel); if( digits > 0 )
{
pi.Append("."); for( int i = 0; i < digits; i += 9 )
{
int nineDigits = NineDigitsOfPi.StartingAt(i+1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format("{0:D9}", nineDigits);
pi.Append(ds.Substring(0, digitCount)); // Show progress (checking for Cancel)
//显示进度(检查是否取消)
ShowProgress(pi.ToString(), digits, i + digitCount, out cancel);
if( cancel ) break;
}
}
} delegate void CalcPiDelegate(int digits); private void _calcButton_Click(object sender, System.EventArgs e)
{
// Synch method
// CalcPi((int)_digits.Value);
// return; // Calc button does double duty as Cancel button
//Calc 按钮兼有 Cancel 按钮的功能
switch( _state )
{
// Start a new calculation
// 开始新的计算
case CalcState.Pending:
// Allow canceling
//允许取消计算
_state = CalcState.Calculating;
_calcButton.Text = "取消"; // Asynch delegate method
// 异步委托方法
CalcPiDelegate calcPi = new CalcPiDelegate(CalcPi);
calcPi.BeginInvoke((int)_digits.Value, null, null);
break; // Cancel a running calculation
//取消正在运行的计算
case CalcState.Calculating:
_state = CalcState.Canceled;
_calcButton.Enabled = false;
break; // Shouldn't be able to press Calc button while it's canceling
// 在取消过程中应该无法按下 Calc 按钮
case CalcState.Canceled:
Debug.Assert(false);
break;
}
} private void btnShowThead_Click(object sender, System.EventArgs e)
{
tbShowThread.Text="";
Process[] allProcs=Process.GetProcesses();
String tempString="";
foreach(Process proc in allProcs)
{
ProcessThreadCollection myThreads=proc.Threads;
tempString+="进程:"+proc.ProcessName+" 进程ID"+proc.Id +" \r\n" ;
//tbShowThread.Text +=tempString;
foreach(ProcessThread pt in myThreads)
{
DateTime startTime=pt.StartTime;
TimeSpan cpuTime=pt.TotalProcessorTime;
int priority=pt.BasePriority;
//ThreadState ts=pt.ThreadState;
tempString+=" 线程ID:"+pt.Id+" 开始时间:"+startTime.ToString()+"\r\n CPU时间:"+cpuTime+" 优先权:"+priority+"\r\n";
//tbShowThread.Text +=tempString;
}
}
tbShowThread.Text +=tempString;
} private void btnShowPro_Click(object sender, System.EventArgs e)
{
tbShowThread.Text="";
Process[] allProcs=Process.GetProcesses();
String tempString="";
foreach(Process proc in allProcs)
{
ProcessThreadCollection myThreads=proc.Threads;
tempString+="进程:"+proc.ProcessName+" 进程ID"+proc.Id +" \r\n" ;
}
tbShowThread.Text +=tempString;
}
}
}