The best way to do nothing until something is related to C #

I was looking at the code to connect to the database in one of the applications 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 bothers me. Is there a better way to do anything until everything is connected?

EDIT:

The compound is obtained as follows

private static IDbConnection GetConnection()
{
     return new SqlConnection(ConfigurationManager.ConnectionStrings["CoonectionStringName"].ConnectionString);
}
+5
source share
4 answers

- , , , ; . while , Windows , , , , , , .

, Thread.Yield(), , , , . , , , , . ; :

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.
}
+5

EDIT. , DbConnection, IDbConnection

StateChange DbConnection while.

this

+2

, -, , , . , .

var startTime = DateTime.Now;
var endTime = DateTime.Now.AddSeconds(5);
var timeOut = false;

while (_dbConnection.State == ConnectionState.Connecting)
{
    if (DateTime.Now.Compare(endTime) >= 0
    {
        timeOut = true;
        break;
    }
}

if (timeOut)
{
    // TODO: Handle your time out here.
}
+1

Connect the StateChange event handler. When the state is open, do what you need.

            m_SqlConnection = new SqlConnection(ConnectionStringBuilder.ConnectionString);
            m_SqlConnection.StateChange += new System.Data.StateChangeEventHandler(m_SqlConnection_StateChange);
            m_SqlConnection.Open();



    void m_SqlConnection_StateChange(object sender, System.Data.StateChangeEventArgs e)
    {
        try
        {
            if (m_SqlConnection.State == ConnectionState.Open)
            {
                //do stuff
            }
            if (m_SqlConnection.State == ConnectionState.Broken)
            {
                Close();
            }
            if (m_SqlConnection.State == ConnectionState.Closed)
            {
                Open();
            }
        }
        catch
        {

        }
    }
0
source

All Articles