在我正在开发的一个应用程序中,我查看了用于连接到数据库的代码,我看到了以下内容
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);
}发布于 2011-06-14 03:37:49
虽然循环确实有效,并且是等待一些后台操作的有效策略,但其他答案似乎遗漏了一个关键点;您必须让后台操作来做一些工作。在while循环中翻转效率不是很高,但Windows会认为应用程序的主线程(可能就是正在等待的线程)非常重要,并且在后台操作获得CPU时间的单个时钟之前,会在循环中旋转数百或数千次。
要避免这种情况,请使用Thread.Yield()语句告诉处理器在等待CPU时间的所有其他线程中旋转,并在它们完成时返回。这允许计算机在你等待后台进程的同时完成一些工作,而不是独占CPU通过一个基本上为空的循环。这真的很简单;这是Justin修改后的答案:
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.
}发布于 2011-06-14 03:15:21
编辑:请注意,这适用于DbConnection,而不是IDbConnection
您可以始终使用DbConnection类的StateChange事件,而不是while循环。
检查this
发布于 2011-06-14 03:13:48
考虑到这是一个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.
}https://stackoverflow.com/questions/6335034
复制相似问题