答案:通过订阅 SqlConnection.StateChange 事件可监控连接状态变化,结合 State 属性判断当前状态,但真实连接健康需执行轻量查询验证。

在C#中监控数据库连接状态,主要依赖于所使用的数据库提供程序。以最常见的 SqlConnection(用于 SQL Server)为例,.NET Framework 和 .NET Core/.NET 5+ 提供了直接的方式来感知连接状态的变化。
这是监控连接状态最核心的机制。当连接的 State 属性发生变化时(例如从 Closed 变为 Open,或从 Open 变为 Closed),会触发此事件。
你可以订阅这个事件,在连接打开或关闭时执行自定义逻辑,比如记录日志、更新UI状态或重试连接。
示例代码:
using System;
using System.Data;
using Microsoft.Data.SqlClient; // 或 using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=TestDB;Integrated Security=true;";
using (var connection = new SqlConnection(connectionString))
{
// 订阅 StateChange 事件
connection.StateChange += Connection_StateChange;
try
{
connection.Open();
Console.WriteLine("连接已打开");
// 模拟一些操作
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
Console.WriteLine($"连接失败: {ex.Message}");
}
finally
{
// 显式关闭连接,会触发 StateChange
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
}
// 事件处理方法
static void Connection_StateChange(object sender, StateChangeEventArgs e)
{
Console.WriteLine($"连接状态变化: 从 '{e.OriginalState}' 变为 '{e.CurrentState}'");
if (e.CurrentState == ConnectionState.Open)
{
Console.WriteLine("✅ 数据库连接已成功建立。");
}
else if (e.CurrentState == ConnectionState.Closed)
{
Console.WriteLine("❌ 数据库连接已关闭。");
}
}
}除了事件监听,你也可以通过 Connection.State 属性来获取当前连接的状态。它返回一个 ConnectionState 枚举值,常见值包括:
简单判断示例:
if (connection.State == ConnectionState.Open)
{
Console.WriteLine("连接正常");
}
else
{
Console.WriteLine("连接未打开或已断开");
}虽然有 StateChange 事件,但要注意:
基本上就这些。StateChange 适合监听显式的打开/关闭动作,而真正的连接存活检测还需结合实际操作中的异常处理。
以上就是C#中如何监控数据库连接状态?有什么事件可用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号