gpt4 book ai didi

C# - Thread.Join(Milliseconds) 和 finally block

转载 作者:行者123 更新时间:2023-12-03 13:18:04 26 4
gpt4 key购买 nike

我正在使用 .NET 2.0,如果线程超时,finally block 似乎不会被执行。例如,如果我看到消息“子线程超时...”,我将看不到消息“终于 block 开始...”。这意味着可能没有正确清理数据库对象 (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);
}
}

最佳答案

如果该线程不再需要做任何重要的事情,您应该只中止该线程。在其他情况下,我建议设置某种通知(即在线程上设置 bool 属性),以使您的线程正常关闭。话虽如此,根据documentation finally block 应该在 .NET 2.0 中执行:

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

对于正在发生的事情,我最好的猜测是主线程在您的线程上的 finally block 有机会执行之前退出。尝试输入 Thread.Sleep在中止您的线程以查看是否会改变行为之后。

编辑:
我用 .NET 2.0 编写了一个简单的示例,它产生以下输出,表明 finally block 已执行。

活蹦乱跳的

活蹦乱跳的

活蹦乱跳的

异常(exception)

最后

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);
}
}

关于C# - Thread.Join(Milliseconds) 和 finally block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4056234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com