zoukankan      html  css  js  c++  java
  • 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

    1. public Thread(ThreadStart start)
    2. public Thread(ThreadStart start,int maxStackSize)
    3. public Thread(ParameterizedThreadStart start)
    4. 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
    这就是
  • 相关阅读:
    jQuery.delegate() 函数详解
    java中的Class.forName的作用
    java Map及Map.Entry详解
    SQL Case when 的使用方法
    SpringBoot入门篇--对于JSON数据的返回以及处理二
    SpringBoot入门篇--对于JSON数据的返回以及处理一
    SpringBoot入门篇--使用IDEA创建一个SpringBoot项目
    数据结构和算法之栈和队列三:自定义一个栈包含min函数
    数据结构和算法之栈和队列二:栈的压入,弹出序列
    数据结构和算法之栈和队列一:两个栈模拟一个队列以及两个队列模拟一个栈
  • 原文地址:https://www.cnblogs.com/zhangrCsharp/p/7695588.html
Copyright © 2011-2022 走看看