线程被定义为程序的执行路径。每个线程都定义了一个独特的控制流程。如果应用程序涉及复杂和耗时的操作,那么设置不同的执行路径或线程通常有助于每个线程执行特定的作业。
线程是轻量级的进程。使用线程的一个常见示例是通过现代操作系统实现并发编程。使用线程节省了cpu周期并提高了应用程序的效率。
到目前为止,我们编写了单个线程作为单个进程运行的程序,它是应用程序的运行实例。 但是,这样应用程序可以一次执行一个作业。为了使它一次执行多个任务,它可以分为较小的线程。
当创建system.threading.thread类的对象时,线程的生命周期将会启动,当线程终止或完成执行时,该循环将结束。
以下是线程生命周期中的各种状态:
start方法的情况。sleep方法已被调用wait方法已被调用在 c# 中,system.threading.thread类用于处理线程。它允许在多线程应用程序中创建和访问单个线程。在进程中执行的第一个线程称为主线程。
当 c# 程序开始执行时,主线程就会被自动创建。使用thread类创建的线程称为主线程的子线程。可以使用thread类的currentthread属性访问线程。
以下程序演示主线程执行:
using system;
using system.threading;
namespace multithreadingapplication
{
class mainthreadprogram
{
static void main(string[] args)
{
thread th = thread.currentthread;
th.name = "mainthread";
console.writeline("this is {0}", th.name);
console.readkey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
this is mainthread
下表显示了thread类的一些最常用的属性:
| 属性 | 描述 |
|---|---|
| currentcontext | 获取当前正在执行的线程的上下文。 |
| currentculture | 获取或设置当前线程的文化(culture)。 |
| currentprinciple | 获取或设置线程的当前主体(用于基于角色的安全性)。 |
| currentthread | 获取当前正在运行的线程。 |
| currentuiculture | 获取或设置资源管理器使用的当前文化(culture),以便在运行时查找特定于文化的资源。 |
| executioncontext | 获取一个executioncontext对象,该对象包含有关当前线程的各种上下文的信息。 |
| isalive | 获取指示当前线程的执行状态的值。 |
| isbackground | 获取或设置一个值,指示线程是否是后台线程。 |
| isthreadpoolthread | 获取一个值,指示线程是否属于托管线程池。 |
| managedthreadid | 获取当前受管线程的唯一标识符。 |
| name | 获取或设置线程的名称。 |
| priority | 获取或设置一个指示线程的调度优先级的值。 |
| threadstate | 获取包含当前线程的状态的值。 |
下表显示了thread类最常用的一些方法:
| 序号 | 方法 | 描述 |
|---|---|---|
| 1 | public void abort() |
在调用它的线程中引发threadabortexception异常,以开始终止线程的进程。调用此方法通常会终止线程。 |
| 2 | public static localdatastoreslot allocatedataslot() |
在所有线程上分配一个未命名的数据槽。为了获得更好的性能,请使用标记为threadstaticattribute属性的字段。 |
| 3 | public static localdatastoreslot allocatenameddataslot(string name) |
在所有线程上分配一个命名的数据槽。为了获得更好的性能,请使用标记为threadstaticattribute属性的字段。 |
| 4 | public static void begincriticalregion() |
通知主机执行即将进入的代码区域,线程中止或未处理的异常的影响可能会危及应用程序域中的其他任务。 |
| 5 | public static void beginthreadaffinity() |
通知托管代码即将执行依赖于当前物理操作系统线程标识的指令。 |
| 6 | public static void endcriticalregion() |
通知主机即将执行即将进入的代码区域,线程中止或未处理异常的影响限于当前任务。 |
| 7 | public static void endthreadaffinity() |
通知托管代码已完成执行依赖于当前物理操作系统线程标识的指令的主机。 |
| 8 | public static void freenameddataslot(string name) |
消除进程中所有线程的名称和插槽之间的关联。为了获得更好的性能,请使用标记为threadstaticattribute属性的字段。 |
| 9 | public static object getdata(localdatastoreslot slot) |
从当前线程的当前域中指定插槽中检索值。为了获得更好的性能,请使用标记为threadstaticattribute属性的字段。 |
| 10 | public static appdomain getdomain() |
返回当前线程正在运行的当前域。 |
| 11 | public static appdomain getdomainid() |
返回唯一的应用程序域标识符 |
| 12 | public static localdatastoreslot getnameddataslot(string name) |
查找一个命名的数据槽。为了获得更好的性能,请使用标记为threadstaticattribute属性的字段。 |
| 13 | public void interrupt() |
中断处于waitsleepjoin线程状态的线程。 |
| 14 | public void join() |
阻止调用线程直到线程终止,同时继续执行标准com和sendmessage抽取。此方法具有不同的重载形式。 |
| 15 | public static void memorybarrier() |
同步存储器访问如下:执行当前线程的处理器无法重新排序指令,使得在调用memorybarrier之前进行的存储器访问在内存访问之后执行,这些内存访问之后对memorybarrier的调用。 |
| 16 | public static void resetabort() |
取消当前线程中止请求。 |
| 17 | public static void setdata(localdatastoreslot slot, object data) |
为当前正在运行的线程的当前域设置指定槽中的数据。为了获得更好的性能,请改用标记为threadstaticattribute属性的字段。 |
| 18 | public void start() |
开始一个线程 |
| 19 | public static void sleep(int millisecondstimeout) |
使线程暂停一段时间 |
| 20 | public static void spinwait(int iterations) |
使线程等待iterations参数定义的次数 |
| 21 | public static byte volatileread(ref byte address),public static double volatileread(ref double address),public static int volatileread(ref int address),public static object volatileread(ref object address) |
读取一个字段的值。该值是计算机中任何处理器写入的最新值,它不考虑处理器数量或处理器高速缓存的状态。此方法具有不同的重载形式。上面只给出了几个。 |
| 22 | public static void volatilewrite(ref byte address,byte value);public static void volatilewrite(ref double address, double value);public static void volatilewrite(ref int address, int value);public static void volatilewrite(ref object address, object value) |
立即将值写入字段,以便该值对计算机中的所有处理器可见。此方法具有不同的重载形式。上面只给出了几个。 |
| 23 | public static bool yield() |
使调用线程对另一个准备在当前处理器上运行的线程执行执行。操作系统选择要产生的线程。 |
实现线程是通过扩展thread类创建的。扩展thread类然后调用start()方法来开始执行子线程。
以下程序演示了上面所说的概念:
using system;
using system.threading;
namespace multithreadingapplication
{
class threadcreationprogram
{
public static void calltochildthread()
{
console.writeline("child thread starts");
}
static void main(string[] args)
{
threadstart childref = new threadstart(calltochildthread);
console.writeline("in main: creating the child thread");
thread childthread = new thread(childref);
childthread.start();
console.readkey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
in main: creating the child thread
child thread starts
thread类提供了各种管理线程的方法。
以下示例演示了如何使用sleep()方法在特定时间段内暂停线程。
using system;
using system.threading;
namespace multithreadingapplication
{
class threadcreationprogram
{
public static void calltochildthread()
{
console.writeline("child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
console.writeline("child thread paused for {0} seconds", sleepfor / 1000);
thread.sleep(sleepfor);
console.writeline("child thread resumes");
}
static void main(string[] args)
{
threadstart childref = new threadstart(calltochildthread);
console.writeline("in main: creating the child thread");
thread childthread = new thread(childref);
childthread.start();
console.readkey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
in main: creating the child thread
child thread starts
child thread paused for 5 seconds
child thread resumes
abort()方法用于销毁线程。运行时通过抛出threadabortexception来中止线程。这个异常不能被捕获,控件发送到finally块(如果有的话)。
以下一个实现线程的程序:
using system;
using system.threading;
namespace multithreadingapplication
{
class threadcreationprogram
{
public static void calltochildthread()
{
try
{
console.writeline("child thread starts");
// do some work, like counting to 10
for (int counter = 0; counter <= 10; counter++)
{
thread.sleep(500);
console.writeline(counter);
}
console.writeline("child thread completed");
}
catch (threadabortexception e)
{
console.writeline("thread abort exception");
}
finally
{
console.writeline("couldn't catch the thread exception");
}
}
static void main(string[] args)
{
threadstart childref = new threadstart(calltochildthread);
console.writeline("in main: creating the child thread");
thread childthread = new thread(childref);
childthread.start();
//stop the main thread for some time
thread.sleep(2000);
//now abort the child
console.writeline("in main: aborting the child thread");
childthread.abort();
console.readkey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
in main: creating the child thread
child thread starts
0
1
2
in main: aborting the child thread
thread abort exception
couldn't catch the thread exception