gpt4 book ai didi

c# - 为什么代码在查询数据库时会耗尽 CPU?

转载 作者:行者123 更新时间:2023-11-30 19:11:05 25 4
gpt4 key购买 nike

下面我的 C# 代码检查 SQL 数据库以查看记录是否与 ClientID 和用户名匹配。如果找到超过 15 条或更多的匹配记录,则在执行以下 C# 代码时找到 15 条记录时,我的 Windows 2008 服务器上的 CPU 峰值约为 78%。 SQL Server 2008 数据库和软件位于另一台服务器上,因此问题不在于 SQL Server 占用 CPU。问题出在我的 C# 软件上,它正在执行下面的代码。在执行数据库查询并找到记录时,我可以看到包含以下 C# 代码的我的软件可执行文件达到 78%。

如果我的代码有问题导致 CPU 在找到 15 条或更多匹配记录时出现峰值,有人能告诉我吗?您能否告诉我/展示如何优化我的代码?

更新:如果它找到 10 条记录,CPU 只会以 2-3% 的速度峰值。只有当它找到 15 条或更多记录时,CPU 才会达到 78% 的峰值并持续两到三秒。

//ClientID[0] will contain a ClientID of 10 characters
//output[0] will contain a User Name
char[] trimChars = { ' ' };
using (var connection = new SqlConnection(string.Format(GlobalClass.SQLConnectionString, "History")))
{
connection.Open();
using (var command = new SqlCommand())
{
command.CommandText = string.Format(@"SELECT Count(*) FROM Filelist WHERE [ToAccountName] = '" + output[0] + @"'");
command.Connection = connection;
var rows = (int) command.ExecuteScalar();
if (rows >= 0)
{
command.CommandText = string.Format(@"SELECT * FROM Filelist WHERE [ToAccountName] = '" + output[0] + @"'");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
//Make sure ClientID does NOT exist in the ClientID field
if (reader["ClientID"].ToString().TrimEnd(trimChars).IndexOf(ClientID[0]) !=
-1)
{
//If we are here, then do something
}
}
}
reader.Close();
reader.Dispose();
}
}
// Close the connection
if (connection != null)
{
connection.Close();
}
}
}

最佳答案

如果要删除第一个查询,您可以将数据库访问次数从 2 减少到 1,这不是必需的。

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT ClientID FROM dbo.Filelist WHERE ToAccountName = @param"; // note single column in select clause
command.Parameters.AddWithValue("@param", output[0]); // note parameterized query

connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read()) // reader.HasRow is doubtfully necessary
{
// logic goes here
// but it's better to perform it on data layer too

// or return all clients first, then perform client-side logic
yield return reader.GetString(0);
}
} // note that using block calls Dispose()/Close() automatically
}

关于c# - 为什么代码在查询数据库时会耗尽 CPU?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13432631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com