C# Thread详解

一、类Thread的定义

public sealed partial class Thread : CriticalFinalizerObject

Thread类只继承了一个抽象类CritiacalFinalizerObject

二、Thread内部的定义的类

1、StartHelper类

1.1、类StartHelper的定义

private sealed class StartHelper

1.2、类StartHelper中的定义的字段

//该线程中允许使用的最大栈深
internal int _maxStackSize;
//该字段用于保存创建线程时传入的委托
internal Delegate _start;
//该字段用于保存通过调用start方法传入的参数(提供该给委托使用的参数)
internal object? _startArg;
//使用的文化信息
internal CultureInfo? _culture;
internal CultureInfo? _uiCulture;
//使用的执行上下文
internal ExecutionContext? _executionContext;
//public delegate void ContextCallback(object? state);
//internal delegate void ContextCallback<TState>(ref TState state);
//ContextCallback是一个委托声明
internal static readonly ContextCallback s_threadStartContextCallback = new ContextCallback(Callback);

1.3、类StartHelper中的方法

1.3.1、Run方法
[MethodImpl(MethodImplOptions.AggressiveInlining)] // avoid long-lived stack frame in many threads
internal void Run(){
	if (_executionContext != null && !_executionContext.IsDefault){
		//如果指定了执行上下文(_exectuionContext不为null,且不为默认的执行上下文),只是用指定的上下文执行委托
		ExecutionContext.RunInternal(_executionContext, s_threadStartContextCallback, this);
	}else{
		//如果没有指定的上下文或者指定的是默认的上文则直接调用RunWork执行委托
        RunWorker();
	}
}

注:ExecutionContext的相关内容见https://editor.csdn.net/md/?articleId=117068899

1.3.2、RunWorker方法

该方法中真正执行了委托

  [MethodImpl(MethodImplOptions.AggressiveInlining)] // avoid long-lived stack frame in many threads
private void RunWorker(){
	//初始化线程使用的语言环境
	InitializeCulture();
	//获取保存在StartHelper中的委托的副本
	Delegate start = _start;
	//清空_start
	_start = null!;
 
#if FEATURE_OBJCMARSHAL
	if (AutoreleasePool.EnableAutoreleasePool){
		//创建自动释放的pool
		AutoreleasePool.CreateAutoreleasePool();
	}
#endif
	if (start is ThreadStart threadStart){
		//如果传入的是不需要参数的委托,则直接运行委托
		threadStart();
    }else{
    	//程序运行到这里说明创建thread实例时传入的是一个需要参数的委托
        ParameterizedThreadStart parameterizedThreadStart = (ParameterizedThreadStart)start;
        //获取有start方法传入的参数
 		object? startArg = _startArg;
		_startArg = null;
		//执行委托
		parameterizedThreadStart(startArg);
     }
#if FEATURE_OBJCMARSHAL
     //如果该部分执行过程中出现了异常,进程会直接终止,所以没有必要将
     //该部分代码包裹在finally块中。
	if (AutoreleasePool.EnableAutoreleasePool){
		AutoreleasePool.DrainAutoreleasePool();
    }
#endif
}
1.3.3、Callback方法
 private static void Callback(object? state){
	Debug.Assert(state != null);
	//调用StartHelper对象的RunWorker方法
	((StartHelper)state).RunWorker();
}

2、值类型的ThreadHandle

 internal readonly struct ThreadHandle{
	private readonly IntPtr _ptr;
	internal ThreadHandle(IntPtr pThread){
            _ptr = pThread;
    }
}

二、Thread中定义的字段

//同步上下文
internal SynchronizationContext? _synchronizationContext; // maintained separately from ExecutionContext
//执行上下文
internal ExecutionContext? _executionContext;
//线程名
private string? _name;
//里面封装了创建Thread实例时传入的委托,以及执行委托的逻辑
private StartHelper? _startHelper;
#pragma warning disable CA1823, 169 // These fields are not used from managed.
        // IntPtrs need to be together, and before ints, because IntPtrs are 64-bit
        // fields on 64-bit platforms, where they will be sorted together.
        private IntPtr _DONT_USE_InternalThread; // Pointer
        //线程优先级
        private int _priority; // INT32
        //线程id
        private int _managedThreadId; // INT32
#pragma warning restore CA1823, 169
//如果当前线程是一个线程池线程,并且在执行任务的过程中线程的状态被修改了
//(name, background state, or priority等),则可以通过该标志快速判断是否需要重置线程的状态
private bool _mayNeedResetForThreadPool;

三、构造函数

//接收一个无参的委托
public Thread(ThreadStart start) {
    if (start == null) {
    	//如果委托为null则抛出异常
        throw new ArgumentNullException(nameof(start));
    }
    //创建封装当前委托的StartHelper
    _startHelper = new StartHelper(start);
	//初始化
    Initialize();
}
//接收一个有参委托
public Thread(ParameterizedThreadStart start) {
    if (start == null) {
        throw new ArgumentNullException(nameof(start));
    }
    _startHelper = new StartHelper(start);
    Initialize();
}

构造函数中定义的Initialize方法是一个外部方法,其声明如下:

[MethodImpl(MethodImplOptions.InternalCall)]
private extern void Initialize();

四、Thread中start的方法

1、无参数的start

 public void Start() => Start(captureContext: true);
 private void Start(bool captureContext) {
 	//获取当前的线程中的_startHelper
    StartHelper? startHelper = _startHelper;

    // In the case of a null startHelper (second call to start on same thread)
    // StartCore method will take care of the error reporting.
    if (startHelper != null) {
    	//如果当前线程中的startHelper不为null表明该线程还没有被执行过
    	//将参数置空
        startHelper._startArg = null;
        //如果需要使用相同的上下文执行接下类的任务则捕获当前线程中的executionContext,
        //否则当前线程的executionContext置空
        startHelper._executionContext = captureContext ? ExecutionContext.Capture() : null;
    }
	//
    StartCore();
}

2、有参数的start

public void Start(object? parameter) => Start(parameter, captureContext: true);
[UnsupportedOSPlatform("browser")]
public void UnsafeStart(object? parameter) => Start(parameter, captureContext: false);

private void Start(object? parameter, bool captureContext) {
    StartHelper? startHelper = _startHelper;
    if (startHelper != null) {
        if (startHelper._start is ThreadStart) {
            //如果是无参的委托则抛出异常
            throw new InvalidOperationException(SR.InvalidOperation_ThreadWrongThreadStart);
        }
        //获取委托需要的参数
        startHelper._startArg = parameter;
        startHelper._executionContext = captureContext ? ExecutionContext.Capture() : null;
    }
    StartCore();
}

3、正式执行线程

//获取线程本地指针,并执行线程(或许可理解为将线程交给系统去处理)
private unsafe void StartCore(){
	lock (this) {
         fixed (char* pThreadName = _name){
             StartInternal(GetNativeHandle(), _startHelper?._maxStackSize ?? 0, _priority, pThreadName);
         }
    }
}
 //获取线程的本地指针
internal ThreadHandle GetNativeHandle() {
    IntPtr thread = _DONT_USE_InternalThread;
    // This should never happen under normal circumstances.
    if (thread == IntPtr.Zero) {
        throw new ArgumentException(null, SR.Argument_InvalidHandle);
    }
	//ThreadHandle封装了获取的thread的本地指针
    return new ThreadHandle(thread);
} 

StartInternal是一个外部方法,其声明如下:

 [DllImport(RuntimeHelpers.QCall)]
private static extern unsafe void StartInternal(ThreadHandle t, 
				int stackSize, int priority, char* pThreadName);

五、方法流程图

1、Thread中Start方法的流程图
Start方法的流程图
2、StartHelper中Run方法的流程图
StartHelper中Run方法的流程图

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值