/// <summary> /// Dispose /// </summary> public void Dispose() { try { lock (this._threadLock) { if (this._disposed) { return; } this._disposed = true; if (this._runing) { this._threadStartPara.Cancell(); this.PrimitiveAbort(null); this._threadStartPara.Dispose(); this._threadStartPara = null; this._thread = null; this._runing = false; } } } catch (Exception ex) { Loger.Error(ex); } }
/// <summary> /// 启动线程 /// </summary> /// <param name="obj">线程启动参数</param> /// <param name="apartmentState">指定的单元状态 System.Threading.Thread</param> public void Start(object obj = null, ApartmentState apartmentState = ApartmentState.Unknown) { lock (this._threadLock) { if (this._disposed) { throw new ObjectDisposedException(string.Empty, "对象已释放"); } if (this._runing) { return; } this._threadStartPara = new ThreadStartPara(obj); this._thread = new Thread(new ParameterizedThreadStart(this.ThreadExcuteMethod)); this._thread.SetApartmentState(apartmentState); if (string.IsNullOrWhiteSpace(this._name)) { var st = new System.Diagnostics.StackTrace(1, true); var sf = st.GetFrame(0); var method = sf.GetMethod(); this._thread.Name = string.Format("{0}.{1}.{2}.{3}", sf.GetFileName(), sf.GetFileLineNumber(), method.DeclaringType.FullName, method.Name); } else { this._thread.Name = this._name; } this._thread.IsBackground = this._isBackground; this._runing = true; this._thread.Start(this._threadStartPara); } }
/// <summary> /// 终止线程 /// </summary> /// <param name="stateInfo">An object that contains application-specific information, such as state, which can be used by the thread being aborted</param> public void Abort(object stateInfo = null) { lock (this._threadLock) { if (this._runing) { this._threadStartPara.Cancell(); this.PrimitiveAbort(stateInfo); this._threadStartPara.Dispose(); this._threadStartPara = null; this._thread = null; this._runing = false; } } }
/// <summary> /// 停止线程 /// </summary> /// <param name="sycn">是否同步调用停止方法,同步调用会等线程结束后才退出本方法[true:同步;false:异步]</param> /// <param name="synMillisecondsTimeout">同步超时时间,-1表示无限期等待,单位/毫秒[isSycn为true时有效]</param> public void Stop(bool sycn = false, int synMillisecondsTimeout = -1) { lock (this._threadLock) { if (this._runing) { this._threadStartPara.Cancell(); if (sycn) { if (!this._threadStartPara.WaitOne(synMillisecondsTimeout)) { //超时终止 this.PrimitiveAbort(); } } this._threadStartPara.Dispose(); this._threadStartPara = null; this._thread = null; this._runing = false; } } }