初探C#多线程编程
以前在使用VB来实现多线程的时候,发现有一定的难度。虽然也有这样那样的方法,但都不尽人意,但在C#中,要编写多线程应用程序却相当的简单。这篇文章将作简要的介绍,以起到抛砖引玉的作用!
.NET将关于多线程的功能定义在System.Threading名字空间中。因此,要使用多线程,必须先声明引用此名字空间(using System.Threading;)。
即使你没有编写多线程应用程序的经验,也可能听说过“启动线程”“杀死线程”这些词,其实除了这两个外,涉及多线程方面的还有诸如“暂停线程”“优先级”“挂起线程”“恢复线程”等等。下面将一个一个的解释。
a.启动线程
顾名思义,“启动线程”就是新建并启动一个线程的意思,如下代码可实现:
Thread thread1 = new Thread(new ThreadStart( Count));
其中的 Count 是将要被新线程执行的函数。
b.杀死线程
“杀死线程”就是将一线程斩草除根,为了不白费力气,在杀死一个线程前最好先判断它是否还活着(通过 IsAlive 属性),然后就可以调用 Abort 方法来杀死此线程。
c.暂停线程
它的意思就是让一个正在运行的线程休眠一段时间。如 thread.Sleep(1000); 就是让线程休眠1秒钟。
d.优先级
这个用不着解释了。Thread类中有一个ThreadPriority属性,它用来设置优先级,但不能保证操作系统会接受该优先级。一个线程的优先级可分为5种:Normal, AboveNormal, BelowNormal, Highest, Lowest。具体实现例子如下:
thread.Priority = ThreadPriority.Highest;
e.挂起线程
Thread类的Suspend方法用来挂起线程,知道调用Resume,此线程才可以继续执行。如果线程已经挂起,那就不会起作用。
if (thread.ThreadState = ThreadState.Running)
{
thread.Suspend();
}
f.恢复线程
用来恢复已经挂起的线程,以让它继续执行,如果线程没挂起,也不会起作用。
if (thread.ThreadState = ThreadState.Suspended)
{
thread.Resume();
}
下面将列出一个例子,以说明简单的线程处理功能。此例子来自于帮助文档。
using System;
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();
}
}
此代码产生的输出类似如下内容:
Main thread: Start a second thread.
Main thread: Do some work.
ThreadProc: 0
Main thread: Do some work.
ThreadProc: 1
Main thread: Do some work.
ThreadProc: 2
Main thread: Do some work.
ThreadProc: 3
Main thread: Call Join(), to wait until ThreadProc ends.
ThreadProc: 4
ThreadProc: 5
ThreadProc: 6
ThreadProc: 7
ThreadProc: 8
ThreadProc: 9
Main thread: ThreadProc.Join has returned. Press Enter to end program.
在开发中经常会遇到线程的例子,如果某个后台操作比较费时间,我们就可以启动一个线程去执行那个费时的操作,同时程序继续执行。在某些情况下可能会出现多个线程的同步协同的问题,下面的例子就展示了在两个线程之间如何协同工作。
这个程序的思路是共同做一件事情(从一个ArrayList中删除元素),如果执行完成了,两个线程都停止执行。
代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
/// <summary>
/// 在开发中经常会遇到线程的例子,如果某个后台操作比较费时间,我们就可以启动一个线程去执行那个费时的操作,同时程序继续执行。在某些情况下可能会出现多个线程的同步协同的问题,下面的例子就展示了在两个线程之间如何协同工作。
///
///这个程序的思路是共同做一件事情(从一个ArrayList中删除元素),如果执行完成了,两个线程都停止执行。
///作者:周公
/// 时间:2008-5-17
/// 原发地址:http://blog.csdn.net/zhoufoxcn
/// </summary>
public class ThreadDemo
{
private Thread threadOne;
private Thread threadTwo;
private ArrayList stringList;
private event EventHandler OnNumberClear;//数据删除完成引发的事件
public static void Main()
{
ThreadDemo demo = new ThreadDemo(1000);
demo.Action();
}
public ThreadDemo(int number)
{
Random random = new Random(1000000);
stringList = new ArrayList(number);
for (int i = 0; i < number; i++)
{
stringList.Add(random.Next().ToString());
}
threadOne = new Thread(new ThreadStart(Run));//两个线程共同做一件事情
threadTwo = new Thread(new ThreadStart(Run));//两个线程共同做一件事情
threadOne.Name = "线程1";
threadTwo.Name = "线程2";
OnNumberClear += new EventHandler(ThreadDemo_OnNumberClear);
}
/// <summary>
/// 开始工作
/// </summary>
public void Action()
{
threadOne.Start();
threadTwo.Start();
}
/// <summary>
/// 共同做的工作
/// </summary>
private void Run()
{
string stringValue = null;
while (true)
{
Monitor.Enter(this);//锁定,保持同步
stringValue = (string)stringList[0];
Console.WriteLine(Thread.CurrentThread.Name + "删除了" + stringValue);
stringList.RemoveAt(0);//删除ArrayList中的元素
if (stringList.Count == 0)
{
OnNumberClear(this, new EventArgs());//引发完成事件
}
Monitor.Exit(this);//取消锁定
Thread.Sleep(5);
}
}
//执行完成之后,停止所有线程
void ThreadDemo_OnNumberClear(object sender, EventArgs e)
{
Console.WriteLine("执行完了,停止了所有线程的执行。");
threadTwo.Abort();
threadOne.Abort();
}
}