1

私は .NET 2.0 を使用していますが、Thread がタイムアウトした場合、finally ブロックが実行されていないようです。たとえば、「子スレッドがタイムアウトしました...」というメッセージが表示された場合、「最終的にブロックが開始されました...」というメッセージは表示されません。これは、データベース オブジェクト (Oracle.DataAccess) が適切にクリーンアップされていない可能性があることを意味します。子スレッド内でクリーンアップを強制する方法はありますか、またはクリーンアップをメイン スレッドに移動し、データベース オブジェクトを子スレッドに渡す必要がありますか?

   private void runThread(string strSP, object objThreadParameter)
    {
        try
        {
            bool blnThreadCompletedOK = true;

            Thread threadHelper = new Thread(getData);
            threadHelper.Start(objThreadParameter);

            // Wait for called thread.  
            blnThreadCompletedOK = threadHelper.Join(THREAD_TIMEOUT);
            if (blnThreadCompletedOK)
            {
                // Thread has completed and should have stopped running.
                // i.e. the thread has processed normally or an exception has been copied to the objExceptionThread object.
                if (objExceptionThread != null)
                {
                    throw objExceptionThread;
                }
            }
            else
            {
                System.Diagnostics.EventLog.WriteEntry("Main thread", "Child Thread Timed Out...", System.Diagnostics.EventLogEntryType.Warning);

                // Main thread has timed out waiting for the child thread.  Likely the child thread is still running.
                if (threadHelper.IsAlive)
                {
                    threadHelper.Abort();  // This will trigger the exception handling in the child thread and cause the finally
                                           // block to be executed.
                }
                throw (new Exception("The call to " + strSP + "() timed out as it exceeded " + (THREAD_TIMEOUT / 1000).ToString() + " seconds"));
            }
        }
        catch (Exception exc)
        {
            throw new PivotalApplicationException(exc.Message, exc, mrsysSystem);
        }
    }


    private void getData(object objThreadParameter)
    {
        OracleCommand oraCmd = null;
        OracleConnection oraConn = null;
        OracleDataReader dr = null;

        try
        {              
            // Initialization.
            int intMAX_RETRIES = 20;       // Maximum number of retries.
            int intRETRY_DROP_POOL = 5;    // At some point, if connections are still failing, try clearing the pool.

            // Other initialization stuff...

            // Now execute the SP.
            for (int i = 1; i <= intMAX_RETRIES; i++)
            {
                try
                {
                    try
                    {
                        // Setup Oracle connection and initialize Oracle command object.
                        getOracleConnection(out oraConn, connString);
                    }
                    catch (Exception exc)
                    {
                        throw new Exception("Error in getData() setting up connection - " + exc.Message);
                    }

                    try
                    {
                        oraCmd = new OracleCommand(strSP, oraConn);
                        setupCommand (out oraCmd);
                    }
                    catch (Exception exc)
                    {
                        throw new Exception("Error in getData() setting up parameters - " + exc.Message);
                    }

                    try
                    {
                        dr = oraCmd.ExecuteReader();
                        break; // Success, so, leave the for loop.
                    }
                    catch (Exception exc)
                    {
                        throw new Exception("Error in getData() executing command.\n\n" + strParametersMsg + " \n\n" + exc.Message);
                    }
                }
                catch (Exception excInner)
                {

                    if (i >= intMAX_RETRIES)
                    {
                        throw new Exception(excInner.Message);
                    }
                    else
                    {
                        // Cleanup oraCmd, oraConn, oraDr...
                    }
                }
            }

            try
            {
                // Process results...
            }
            catch (Exception exc)
            {
                throw new Exception("Error in getData() processing results - " + exc.Message);
            }

            // Now set the variables that are shared between the Main thread and this thread...

        }
        catch (Exception exc)
        {
            logMessage(exc.Source + " " + exc.Message);
            objExceptionThread = exc;  // Initialize exception in Main Thread...
        }
        finally
        {
            System.Diagnostics.EventLog.WriteEntry("Child Thread", "Finally block started...", System.Diagnostics.EventLogEntryType.Warning);

            // With .NET 2.0 and later, the finally block should always be executed correctly for a Thread.Abort()
            if (!(dr == null))
            {
                dr.Dispose();
            }
            if (!(oraCmd == null))
            {
                oraCmd.Dispose();
            }
            if (!(oraConn == null))
            {
                oraConn.Close();
                oraConn.Dispose();
            }

            System.Diagnostics.EventLog.WriteEntry("Child Thread", "Finally block completed...", System.Diagnostics.EventLogEntryType.Warning);
        }
    }
4

3 に答える 3

3

スレッドを中止する必要があるのは、そのスレッドがそれ以上行うべき重要なものがない場合のみです。それ以外の場合は、スレッドを正常にシャットダウンさせる何らかの通知を設定する (つまり、スレッドにブール値のプロパティを設定する) ことをお勧めします。ドキュメントによると、finally ブロックは.NET 2.0 で実行する必要があります。

スレッドを破棄するために Abort メソッドが呼び出されると、共通言語ランタイムは ThreadAbortException をスローします。ThreadAbortException は、キャッチできる特別な例外ですが、catch ブロックの最後で自動的に再度発生します。この例外が発生すると、ランタイムはスレッドを終了する前にすべての finally ブロックを実行します。

何が起こっているかについての私の最善の推測は、スレッドの最終ブロックが実行される前にメインスレッドが終了していることです。スレッドを中止した後に a を入れてみてThread.Sleep、動作が変わるかどうかを確認してください。

編集:私は、finally ブロックが実行されたことを示す次の出力を生成する .NET 2.0 で簡単な例を書きました。

健在で

健在で

健在で

例外

ついに

class ThreadTest
{
    public ThreadTest() { }

    public void test()
    {
        try
        {
            while (true)
            {
                Console.WriteLine("Alive and kicking");
                Thread.Sleep(2000);
            }
        }

        catch (Exception ex)
        {
            Console.WriteLine("Exception");
        }

        finally
        {
            Console.WriteLine("Finally");

        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        ThreadTest myThreadTest = new ThreadTest();
        Thread myThread = new Thread(new ThreadStart(myThreadTest.test));
        myThread.Start();
        Thread.Sleep(5000);
        bool status = myThread.Join(1000);
        if (myThread.IsAlive)
        {
            myThread.Abort();
        }
        Thread.Sleep(5000);
    }
}
于 2010-10-30T00:05:24.100 に答える
1

スレッドがマネージ コード内にある場合にのみ、スレッドを中断できます。ネイティブ コードの場合、ランタイムはThreadAbortException、ネイティブ コードが返されたときに がスローされるようにスケジュールします。その後、finallyブロックが実行されます。ネイティブ関数が戻り、マネージド実行が再開されるまで、finally ブロックは実行されません。

問題がネイティブ コードのハングである場合、finally ブロックは実行できません。

于 2010-10-30T00:28:33.300 に答える
0

ありがとう - 問題はタイミングの 1 つと思われます。threadHelper.IsAlive プロパティを繰り返しチェックしてメイン スレッドを実行し続けると、finally ブロックが実行されます。したがって、コードは dr = oraCmd.ExecuteReader(); でハングしていると思います。Thread.Join() が戻り、Abort() を試みますが、その時点ではできず、メイン スレッドが終了するため、子スレッドも強制終了されます。ただし、接続は開いたままになると思います。

ODP.NET はマネージド データ プロバイダー (http://wiki.oracle.com/page/Oracle+Data+Provider+for+.Net) であると想定されており、コマンド タイムアウト プロパティも備えています。

「CommandTimeout 例外で実行を終了する前に、コマンドの実行が許可される秒数を指定します」。

CommandTimeout が尊重されていないように見える理由をさらに調査します。それでも失敗する場合は、すべての本を持っているように見える人に従って、アプリケーション ドメインの終了を試みるかもしれません。

http://www.albahari.com/threading/part4.aspx#_Aborting_Threads

助けてくれてありがとう!

于 2010-10-30T03:40:47.520 に答える