我的应用程序用于自动恢复数据库。
我创建了一个函数来获取恢复完成的百分比。
问题是执行的次数越多,速度就越慢。我的计算机的性能变得非常糟糕,一切都非常慢。
我认为请求有问题。
private void GetPercentRestore(string dbName, string query)
{
// T-SQL command to have information on the backup
query = query.Replace("'", "''");
string cmd =
$"SELECT sysdb.NAME AS [Name], dmv.PERCENT_COMPLETE AS [PercentComplete] FROM sys.databases sysdb INNER JOIN sys.dm_exec_requests dmv ON sysdb.database_id = dmv.database_id CROSS APPLY sys.dm_exec_sql_text(dmv.SQL_HANDLE) dest WHERE TEXT LIKE '{query}';";
int percent = 0;
int lastPercent = -1;
// Initialize the new connection : need because two query at the same time
SqlConnection conn =
new SqlConnection(
System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionCluster"].ToString());
SqlCommand command = new SqlCommand(cmd, conn);
command.CommandTimeout = 3600;
try
{
while (percent < 100)
{
conn.Open();
// Execute the command
var result = command.ExecuteReader();
// Count the total of the size of the backup
if (result.HasRows)
{
result.Read();
//ProgressBarViewModel e = new ProgressBarViewModel();
percent = Convert.ToInt32(result["PercentComplete"]);
}
else // if not result, assume that Restore is complete
percent = 100;
if (percent != 100)
Thread.Sleep(10000);
result.Close();
conn.Close();
}
}
catch (Exception e)
{
LogFile.WriteError(e.Message);
}
conn.Close();
}
最佳答案
当然,这段代码很慢。您正在为 while 循环的每个循环周期执行以下操作 -
打开 SQL 连接。 (这需要时间,具体取决于您的网络速度)
执行包含INNER JOIN、CROSS APPLY和WHERE子句的查询。
您的第一个选项是在循环之外打开连接。 这将立即提高一些性能。
第二个选项将删除此内联查询并在数据库本身中编写一个存储过程,然后调用该存储过程。
如果您在执行此操作时遇到任何问题,请告诉我。
关于c# - 循环中的 Sql 请求会减慢 C# 应用程序的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44001183/