Rule Definition
Having Thread.Sleep method in a loop in a transaction can increase greatly the time of execution and this is a great risk for the transaction. It can lead to transaction failure.
Remediation
Review the Function / Procedure design.
Violation Code Sample
static public void CreateTransactionScope()
{
try
{
// Create the TransactionScope to execute the commands, guaranteeing
// that both commands can commit or roll back as a single unit of work.
using (TransactionScope scope = new TransactionScope())
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Sleep for 2 seconds.");
Thread.Sleep(2000);
}
Console.WriteLine("Main thread exits.");
// The Complete method commits the transaction. If an exception has been thrown,
// Complete is not called and the transaction is rolled back.
scope.Complete();
}
}
catch (TransactionAbortedException ex)
{
Console.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
}
catch (ApplicationException ex)
{
Console.WriteLine("ApplicationException Message: {0}", ex.Message);
}
}
Fixed Code Sample
static public void CreateTransactionScope()
{
try
{
// Create the TransactionScope to execute the commands, guaranteeing
// that both commands can commit or roll back as a single unit of work.
using (TransactionScope scope = new TransactionScope())
{
// The Complete method commits the transaction. If an exception has been thrown,
// Complete is not called and the transaction is rolled back.
scope.Complete();
}
}
catch (TransactionAbortedException ex)
{
Console.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
}
catch (ApplicationException ex)
{
Console.WriteLine("ApplicationException Message: {0}", ex.Message);
}
}
Reference
https://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/ https://www.daniweb.com/programming/software-development/threads/459731/better-way-to-wait-than-thread-sleep-1-inside-a-loop
Related Technologies
Technical Criterion
CWE-1095 - Loop Condition Value Update within the Loop
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.