スレッドの破棄

マネージ スレッドを完全に停止するには、Abort メソッドを使用します。 Abort を呼び出すと、共通言語ランタイムが対象スレッドに ThreadAbortException をスローします。対象スレッドはこの例外をキャッチできます。 詳細については、「Thread.Abort」を参照してください。

メモメモ

スレッドがアンマネージ コードを実行しているときに、その Abort メソッドが呼び出された場合、ランタイムはスレッドを ThreadState.AbortRequested とマークします。スレッドがマネージ コードに戻ると例外がスローされます。

スレッドは、一度アボートされると、再起動できません。

Abort メソッドを呼び出しても、対象スレッドは ThreadAbortException をキャッチし、finally ブロック内の任意の量のコードを実行できるため、すぐには中止されません。 スレッドが終了するまで待機する必要がある場合は、Thread.Join を呼び出すことができます。 Thread.Join はブロッキング呼び出しで、スレッドが実際に実行を停止するか、オプションのタイムアウト間隔が経過するまで制御が戻りません。 中止されたスレッドは、ResetAbort メソッドを呼び出したり、finally ブロックで非バインド処理を実行したりする可能性があります。そのため、タイムアウトを指定していない場合、待機の終了は保証されません。

Thread.Join メソッドの呼び出しを待機しているスレッドは、Thread.Interrupt を呼び出す他のスレッドによって中断される可能性があります。

ThreadAbortException の処理

独自のコードから Abort を呼び出した結果、またはスレッドが動作しているアプリケーション ドメインをアンロード (AppDomain.UnloadThread.Abort を使用してスレッドを終了します) した結果としてスレッドが中止されるようにする場合、スレッドは、次のコードに示すように ThreadAbortException を処理し、finally 句の最終処理を実行する必要があります。

Try
    ' Code that is executing when the thread is aborted.
Catch ex As ThreadAbortException
    ' Clean-up code can go here.
    ' If there is no Finally clause, ThreadAbortException is
    ' re-thrown by the system at the end of the Catch clause. 
Finally
    ' Clean-up code can go here.
End Try
' Do not put clean-up code here, because the exception 
' is rethrown at the end of the Finally clause.
try 
{
    // Code that is executing when the thread is aborted.
} 
catch (ThreadAbortException ex) 
{
    // Clean-up code can go here.
    // If there is no Finally clause, ThreadAbortException is
    // re-thrown by the system at the end of the Catch clause. 
}
// Do not put clean-up code here, because the exception 
// is rethrown at the end of the Finally clause.

finally 句の末尾、または finally 句が存在しない場合は catch 句の末尾で、ThreadAbortException がシステムによって再スローされるため、catch 句または finally 句にクリーンアップ コードを配置する必要があります。

この例外をシステムが再スローしないようにするには、Thread.ResetAbort メソッドを呼び出します。 ただし、この操作は、独自のコードが原因で ThreadAbortException が生成された場合に限定する必要があります。

参照

参照

ThreadAbortException

Thread

その他の技術情報

スレッドの使用とスレッド処理