这里,我使用Microsoft Performance Monitor来检查我的c#应用程序的凭据句柄。我发现凭证句柄不断增长。您可以打开性能监视器,并在“安全性按进程统计信息”下添加“凭证句柄”计数器。会引起手柄泄漏吗? GC会收集手柄吗?如何使用windbg或其他工具分析此问题?
这是我的示例程序:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DBTest
{
class DBTest2
{
class Program
{
[SuppressMessage("ReSharper", "InconsistentlySynchronizedField")]
static void Work(object data)
{
var dbConn = new SqlConnection("*********");
SqlConnection.ClearPool(dbConn);
dbConn.Open();
string sqlQuery = "SELECT DBName = name FROM master..sysdatabases WHERE name = @DBName";
using (var command = new SqlCommand(sqlQuery, dbConn) { CommandTimeout = 300 })
{
command.Parameters.Add(new SqlParameter("@DBName", SqlDbType.NVarChar) { Direction = ParameterDirection.Input, Value = "***" });
command.ExecuteScalar();
}
dbConn.Close();
}
static void Main(string[] args)
{
Timer tmr = new Timer(Work, "tick...", 1000 * 60 * 1, 30 * 1000);
Console.ReadLine();
tmr.Dispose();
return;
}
}
}
}
也将您的SqlConnection放在using块中:
using (var dbConn = new SqlConnection("*********"))
{
}