Start/Stop というメソッドを使用してスレッドを起動/終了するクラスがあります。Stop メソッドは Threading リソースを適切にクリーンアップしますが、スレッド自体が自然終了または例外で終了した場合は、適切にクリーンアップするために 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));
}
}