System.Threading Namespace命名空间有许多线程有关的类,其中Thread类是必使用的类。线程可以执行分支操作,举例如下:
using System;
using System.Threading;
public class ThreadStartBranching
{
enum UserClass
{
ClassAdmin,
ClassUser
}
static void AdminMethod()
{
Console.WriteLine("Admin Method");
}
static void UserMethod()
{
Console.WriteLine("User Method");
}
static void ExecuteFor(UserClass uc)
{
ThreadStart ts;
ThreadStart tsAdmin = new ThreadStart(AdminMethod);
ThreadStart tsUser = new ThreadStart(UserMethod);
if(uc == UserClass.ClassAdmin)
ts = tsAdmin;
else
ts = tsUser;
Thread t = new Thread(ts);
t.Start();
}
static void Main()
{
// execute in the context of an admin user
ExecuteFor(UserClass.ClassAdmin);
// execute in the context of a regular user
ExecuteFor(UserClass.ClassUser);
Console.ReadLine();
}
}
计时器的使用:计时器可以实现一些同步问题。
他定时的去执行一些代码,如果一捕捉到一些该执行的动作就执行之。主要是依靠TimerCallback 代理定义一个定时器,和TimerCallback 代理并为TimerCallback 传入方法参数。定时器需要传入四个参数:1、TimerCallback 代理,2、TimerCallback所代理方法的参数对象,3、定时器开始工作时间,4、定时执行的时间间隔。例如:
public void TimerTest{
Thread t = new Thread(new ThreadStart(obj.GenerateText));
t.Start();
TimerCallback tmrCallBack = new TimerCallback(obj.GetText);
Timer tmr = new Timer(tmrCallBack, null, TimeSpan.Zero,
TimeSpan.FromSeconds(2));
}
public void GenerateText()
{
。。。。。。
}
public void GetText(object state)
{
。。。。。。
}
不但进程可以生成(下蛋)一个或多个线程,线程本身也以生成(下蛋)多个线程。这叫做Spinning Threads with Threads with Threads
Lifecycle of Threads:
-
Aborted - The thread is in the stopped state, but did not necessarily complete execution
-
AbortRequested - The Abort() method has been called but the thread has not yet received the System.Threading.ThreadAbortexception that will try to terminate it - the thread is not stopped but soon will be.
-
Background - The thread is being executed in the background
-
Running - The thread has started and is not blocked
-
Stopped - The thread has completed all its instructions, and stopped
-
StopRequested - The thread is being requested to stop
-
Suspended - The thread has been suspended
-
SuspendRequested - The thread is being requested to suspend
-
Unstarted - The Start() method has not yet been called on the thread
-
WaitSleepJoin - The thread has been blocked by a call to Wait(), Sleep(), or Join()
我的理解:这些都是线程可能所处的状态,线程的某个操作可以导致当前装态的改变。
其中配套使用的是Sleep()与Interrupt()、Suspend()与Resume()
Join
主要是用于线程同步,当两个线程执行Join()操作时阻塞自己,直到对方线程执行完毕。还要注意Interrupt()操作是引发一个系统异常,在使用时特别注意,他可以被catch()捕获而不能唤醒进程(唤醒进程就是睡眠中的线程捕获到了相应的异常),所以这时小心使用try{}catch{}语句。
线程是要耗费资源的,慎用线程,尽量用最少的线程,特别是不能在循环中创建线程。并不是线程越多越好,线程越多,每个线程一次执行的时间片就会越短。进程大部分时间都发调度线程上,而且每个线程会消耗一定的内存和外部资源。
原址:http://linghuchong168.blog.163.com/blog/static/11465371200731101522202/