8.1.thread
ThreadState
Running
StopRequested
SuspendRequested
Background
Unstarted
Stopped
WaitSleepJoin
Suspended
AbortRequested
Aborted
基本使用
构造函数是传递两种delegate,然后start(object)可以给第二种delegate传递参数
使用一个类来传递参数,而不是直接传递,主要是为了解决线程安全问题
public class ThreadWrapper<T>
{
T data;
public ThreadWrapper(T data){this.data=data;}
public void ThreadMethod(){
Console.WriteLine("{0}",data);
}
}
ThreadWrapper<string> wrapper=new ThreadWrapper<string>("Hello");
Thread t=new Thread(wrapper.ThreadMethod);
t.Start();
IsBackground属性控制是否前台,默认IsBackground=false,即默认创建的都是前台线程
Thread t=new Thread(action){IsBackground=true}; //新建后台线程
后台线程的意思就是只要前台线程结束了,后台线程不论是否执行完毕,都随着前台线程的结束而结束
控制线程
1. 使用Start()方法使得线程处于Running状态,线程开始执行
2. 使用Join() 使线程处于WaitSleepJoin状态,阻塞调用线程,直到某个线程终止或经过了指定时间为止
3. Sleep()使线程处于WaitSleepJoin状态,在经历Sleep()的时间后,线程会再次唤醒
4. Abort()使线程处于ResetAbort状态,会抛出一个ThradAbordException类型的异常
看thread 类代码基本上看不到任何意义,它都是外部实现的,而不是用c#写的
ctor
- public Thread(ThreadStart start)
- public Thread(ThreadStart start,int maxStackSize)
- public Thread(ParameterizedThreadStart start)
- public Thread(ParameterizedThreadStart start,int maxStackSize)
ThreadStart,ParameterizedThreadStart 是两个Delegate
public delegate void ThreadStart();
public delegate void ParameterizedThreadStart(Object obj);
SetStartHelper(Delegate start,int maxStackSize)
ThreadHelper threadStartCallBack = new ThreadHelper(start)
内部调用SetStart
private extern void SetStart(Delegate start,int maxStackSize)
Start()
StackCrawlMark stackMark = StackeCrawlMark.LookForMyCaller;
Start(ref stackMark);
StartInternal(IPrincipal principal,ref StackCrawlMark stackMark)
private extern void StartInternal(IPrincipal principal,ref StackCrawlMark stackMark)
thread.cs 1820行
1. internal delegate Object InternalCrossContextDelegate(Object[] args);
2. internal class ThreadHelper
static ThreadHelper(){}
Delegate
3. internal struct ThreadHandle
private IntPtr m_ptr;
internal ThreadHandle(IntPtr pThread){
m_ptr=pThread;
}
4. public sealed class Thread
5. interal enum StackCrawlMark
1. LookForMe=0
2. LookForMyCaller=1
3. LookForMyCallersCalle=2
4. LookForThread=3
这就是