我有一个使用称为 Start/Stop 的方法启动/终止线程的类。Stop 方法可以正确清理线程资源,但如果线程本身自然终止或出现异常,我需要能够调用 Stop 或其他变体(如果需要)来正确清理。
由于我采用了锁定机制,因此不能从线程方法中调用 Stop。
有没有办法可以在原始上下文中调用 Stop 方法?
private bool Terminate { get; set; }
private object _SyncRoot = new object();
private System.Threading.Thread Thread { get; set; }
private System.Threading.CancellationTokenSource CancellationTokenSource { get; set; }
public bool Start (ProcessorOptions options)
{
bool result = false;
lock (this._SyncRoot)
{
if (this.State == EnumState.Ready)
{
this.Options = options;
if (this.CancellationTokenSource != null)
{
this.CancellationTokenSource.Dispose();
}
this.CancellationTokenSource = new System.Threading.CancellationTokenSource();
//this.CancellationTokenSource.Token.Register(?, null, true);
this.Terminate = false;
this.Thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.Process));
this.Thread.Start();
result = true;
}
}
return (result);
}
public void Stop ()
{
lock (this._SyncRoot)
{
if (this.State == EnumState.Processing)
{
try
{
this.Terminate = true;
this.CancellationTokenSource.Cancel(false);
if (!this.Thread.Join(System.TimeSpan.FromSeconds(1.0D)))
{
this.Thread.Abort();
}
}
finally
{
this.Thread = null;
}
}
}
}
private void Process ()
{
lock (this._SyncRoot)
{
if (this.State != EnumState.Ready)
{
throw (new System.InvalidOperationException("The processor instance is not in a ready state."));
}
}
while (!this.Terminate)
{
lock (this._SyncRoot)
{
if (this.QueuedDocuments.Count == 0)
{
if (this.StopAutomaticallyOnQueueEmpty)
{
// Invoke this.Stop() before breaking.
break;
}
}
}
// Parallel.For uses CancellationTokenSource here.
System.Threading.Thread.Sleep(System.TimeSpan.FromSeconds(0.2D));
}
}