11

私は.NET の信頼性機能について読んでおり、探索する次のクラスを作成しました。ExecuteCodeWithGuaranteedCleanup

class Failing
{
    public void Fail()
    {
        RuntimeHelpers.PrepareConstrainedRegions();
        try
        {
        }
        finally
        {
            RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(Code, Cleanup, "fail");
        }
    }

    private void Code(object message)
    {
        // Some code in here that will cause an exception...
    }

    private void Cleanup(object message, bool something)
    {
        Console.WriteLine(message);
        Console.ReadLine();
    }
}

メソッドのさまざまなコード本体を試しましたCode。これらとその実行結果を以下に示します

OutOfMemoryException-が呼び出されCleanup ない原因

List<string> ss = new List<string>();

while (true)
{
    string s = new string('x', 1000000);

    ss.Add(s);
}

StackOverflowException-が呼び出されCleanup ない原因

Code(message); // recursive call

ExecutionEngineException-が呼び出されCleanup ない原因

Environment.FailFast(message.ToString());

原因ThreadAbortException-Cleanup 呼び出されます (ただし、通常try...finallyはこの例外をキャッチすることもできます)

Thread.CurrentThread.Abort();

だから質問は

  • 私はExecuteCodeWithGuaranteedCleanup正しく使用していますか?
  • ExecuteCodeWithGuaranteedCleanup実際に役立つのはいつですか?
4

1 に答える 1

5

一部の例外はプロセスにとって致命的であり、ユーザー提供のコードの実行は続行されません。メソッドの目的はExecuteCodeWithGuaranteedCleanup、データ構造を一貫した状態に戻すことです。プロセスを停止する方法がなくともプロセスが終了する場合、これには意味がありません。OS (正常に動作していると仮定) は、プロセスが終了する理由に関係なく、プロセスが終了するとカーネル オブジェクトを自動的にクリーンアップします。

Hans が示唆ICLRPolicyManagerしているように、特定のホスト (特に SQL Server) でコードが実行されたときに、このようにどの例外が致命的であるかを判断するために、ホストの が関与します。このドキュメント ページの下部にある素敵なグリッドを参照してください: ICLRPolicyManager::SetActionOnFailure メソッド

于 2011-12-24T01:02:26.407 に答える