Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C-Thread.Join(毫秒)和finally块_C#_Multithreading_Try Catch Finally - Fatal编程技术网

C# C-Thread.Join(毫秒)和finally块

C# C-Thread.Join(毫秒)和finally块,c#,multithreading,try-catch-finally,C#,Multithreading,Try Catch Finally,我使用的是.NET2.0,如果线程超时,finally块似乎不会被执行。例如,如果我看到消息Child Thread Timed Out…,我将不会看到消息Finally block start。。。。这意味着数据库对象Oracle.DataAccess可能未正确清理。有没有办法强制在子线程内部进行清理,或者应该将清理移到主线程并将数据库对象传递给子线程 private void runThread(string strSP, object objThreadParameter)

我使用的是.NET2.0,如果线程超时,finally块似乎不会被执行。例如,如果我看到消息Child Thread Timed Out…,我将不会看到消息Finally block start。。。。这意味着数据库对象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);
        }
    }

只有当某个线程不再需要执行任何重要的操作时,才应该中止该线程。在其他情况下,我建议设置某种通知,即在线程上设置一个布尔属性,使线程正常关闭。话虽如此,根据最终块应在.NET 2.0中执行:

当调用Abort方法销毁线程时,公共语言运行库抛出ThreadAbortException。ThreadAbortException是一个可以捕获的特殊异常,但它将在catch块结束时自动再次引发。当引发此异常时,运行库在结束线程之前执行所有finally块

我对发生的事情的最好猜测是,在线程上的最后一个块有机会执行之前,主线程正在退出。试着加入一个线程。在中止线程后睡觉,看看这是否会改变行为

编辑: 我用.NET2.0编写了一个简单的示例,该示例生成以下输出,显示finally块已执行

活蹦乱跳

活蹦乱跳

活蹦乱跳

例外情况

最后


只有当某个线程不再需要执行任何重要的操作时,才应该中止该线程。在其他情况下,我建议设置某种通知,即在线程上设置一个布尔属性,使线程正常关闭。话虽如此,根据最终块应在.NET 2.0中执行:

当调用Abort方法销毁线程时,公共语言运行库抛出ThreadAbortException。ThreadAbortException是一个可以捕获的特殊异常,但它将在catch块结束时自动再次引发。当引发此异常时,运行库在结束线程之前执行所有finally块

我对发生的事情的最好猜测是,在线程上的最后一个块有机会执行之前,主线程正在退出。试着加入一个线程。在中止线程后睡觉,看看这是否会改变行为

编辑: 我用.NET2.0编写了一个简单的示例,该示例生成以下输出,显示finally块已执行

活蹦乱跳

活蹦乱跳

活蹦乱跳

例外情况

最后


您只能在线程位于托管代码中时中断它。如果是在本机代码中,则运行时会安排在本机代码返回时引发ThreadAbortException。最后,块将在此之后执行。在本机函数返回并恢复托管执行之前,finally块不会运行


如果您的问题是本机代码挂起,则finally块无法运行。

您只能在托管代码中中断线程。如果是在本机代码中,则运行时会安排在本机代码返回时引发ThreadAbortException。最后,块将在此之后执行。在本机函数返回并恢复托管执行之前,finally块不会运行


如果您的问题是本机代码挂起,那么finally块将无法运行。

谢谢-问题似乎确实是时间问题。如果我反复检查threadHelper.IsAlive属性并保持主线程运行,那么finally块将执行。因此,我认为代码挂在dr=oraCmd.ExecuteReader上; Join返回并尝试中止,但当时无法中止,然后主线程结束,子线程也被终止。我认为这确实留下了一个开放的联系

ODP.NET应该是一个托管数据提供程序http://wiki.oracle.com/page/Oracle+Data+Provider+for+.Net,它还具有命令超时属性

CommandTimeout指定在异常终止执行之前允许执行命令的秒数

我将进一步调查为什么CommandTimeout似乎没有得到尊重,如果仍然失败,我可能会尝试根据似乎拥有所有书籍的人终止应用程序域


谢谢你的帮助

谢谢-问题似乎确实在于时机。如果我反复检查threadHelper.IsAlive属性并保持主线程运行,那么finally块将执行。因此,我认为代码挂在dr=oraCmd.ExecuteReader上; Join返回并尝试中止,但可以 't,然后主线程结束,因此子线程也被终止。我认为这确实留下了一个开放的联系

ODP.NET应该是一个托管数据提供程序http://wiki.oracle.com/page/Oracle+Data+Provider+for+.Net,它还具有命令超时属性

CommandTimeout指定在异常终止执行之前允许执行命令的秒数

我将进一步调查为什么CommandTimeout似乎没有得到尊重,如果仍然失败,我可能会尝试根据似乎拥有所有书籍的人终止应用程序域


谢谢你的帮助

原来finally块是在线程上执行的-Oracle SP花了如此长的时间>20分钟,以至于我从来没有等过那么长的时间来查看事件日志消息。结果是finally块是在线程上执行的-Oracle SP花了如此长的时间>20分钟,以至于我从来没有等过那么长的时间来查看事件记录要显示的消息。
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);
    }
}