I was reviewing the code to connect to the DB in one of the applications that I'm working on and I saw this
if (_dbConnection == null)
_dbConnection = GetConnection();
while (_dbConnection.State == ConnectionState.Connecting)
{
//Do Nothing until things are connected.
}
if (_dbConnection.State != ConnectionState.Open)
_dbConnection.Open();
var command = GetCommand(commandType);
command.Connection = _dbConnection;
return command;
The while loop worries me. Is there a better way to Do Nothing until things are connected?
EDIT:
The connection is gotten as follows
private static IDbConnection GetConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["CoonectionStringName"].ConnectionString);
}
If you want your last else to do nothing, you can use the continue keyword inside it. For any conditional you can define the conditional to do nothing by defining an empty code block {} for it or by simply ommit the case.
Empty while loops This ensures that you only perform the check at a reasonable interval.
You cannot leave it empty as its mandatory according to the syntax. You can always use conditions which are always true like “while(1==1) “. But this will make this loop an infinite loop which will keep executing forever unless broken with a “break”.
The body of the while can be empty. This is because a null statement, one that consists only of a semicolon, is syntactically valid in Java.
Though the loop does work and is a valid strategy for waiting on some background operation, other answers seem to miss a key point; you have to let the background operation do some work. Churning through a while loop isn't very productive, but Windows will consider the app's main thread, which is probably what's doing the waiting, to be of high importance, and will spin through the loop hundreds or thousands of times before the background operation ever gets a single clock of CPU time.
To avoid this, use the Thread.Yield() statement to tell the processor to spin through all the other threads awaiting CPU time and come back when they're done. This allows the computer to get some work done while you're waiting on the background process, instead of monopolizing the CPU to spin through a basically empty loop. It's real simple; here's Justin's answer revised:
var startTime = DateTime.Now;
var endTime = DateTime.Now.AddSeconds(5);
var timeOut = false;
while (_dbConnection.State == ConnectionState.Connecting)
{
if (DateTime.Now.CompareTo(endTime) >= 0)
{
timeOut = true;
break;
}
Thread.Yield(); //tells the kernel to give other threads some time
}
if (timeOut)
{
Console.WriteLine("Connection Timeout");
// TODO: Handle your time out here.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With