直到在C#中将事物连接起来为止,什么都不做的最佳方法

| 我正在查看正在连接的应用程序之一中连接到数据库的代码,我看到了
 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;
while循环让我担心。在事物连接好之前,还有什么更好的方法吗? 编辑: 连接如下
private static IDbConnection GetConnection()
{
     return new SqlConnection(ConfigurationManager.ConnectionStrings[\"CoonectionStringName\"].ConnectionString);
}
    
已邀请:
        尽管循环确实起作用,并且是等待某些后台操作的有效策略,但其他答案似乎遗漏了一个关键点。您必须让后台操作完成一些工作。通过while循环搅动的效率不是很高,但是Windows会认为应用程序的主线程(等待中的工作)非常重要,它将在成百上千的循环中循环后台操作获得CPU时间的单个时钟之前的时间。 为了避免这种情况,请使用Thread.Yield()语句告诉处理器旋转所有其他等待CPU时间的线程,并在完成后返回。这样,计算机就可以在等待后台进程的同时完成一些工作,而不必独占CPU来进行基本为空的循环。这真的很简单;这是贾斯汀的答案:
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.
}
    
        编辑:请注意,这适用于
DbConnection
而不是
IDbConnection
您始终可以使用DbConnection类的StateChange事件而不是while循环。 检查一下     
        考虑到这是一个Web应用程序,最好的办法是计算自您尝试连接和转义(如果超过超时时间)以来开始经过的时间。显然,在那时抛出异常或处理情况。
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.
}
    
        将处理程序挂接到StateChange事件上。 当国家开放时,请执行所需的操作。
            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
        {

        }
    }
    

要回复问题请先登录注册