我在c#应用程序中有这段代码:
private bool connected
public void ChangeStatusa()
{
if(connected)
{
label1.Text="Connected"
}else{
label1.Text="Connected"
}
}
我希望在sql server断开连接时自动执行此代码,
我想在后台完成这项工作,而不会影响我的应用程序性能。
基本上,我想在我的应用程序中创建一个系统,负责检查sql server连接,并在连接丢失时自动更改状态。
答案 0 :(得分:2)
您是否通过tcp连接?如果是这样,你可以尝试使用带有异步接收的直接套接字连接:这里是一些代码:
class Program
{
static bool disc = false;
static void Main(string[] args)
{
dbtest dt = new dbtest();
dt.Disconnected += new EventHandler(dt_Disconnected);
dt.Start("10.1.32.97", 1433);
while (!Console.KeyAvailable)
{
Console.WriteLine(disc?"disconnected":"tick");
Thread.Sleep(2000);
}
dt.Stop();
}
static void dt_Disconnected(object sender, EventArgs e)
{
disc = true;
Console.WriteLine("Disconnected");
}
}
public class dbtest
{
byte[] buffer = new byte[10];
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public event EventHandler Disconnected = null;
public void Start(string host, int port)
{
if(s!=null)
{
Stop();
}
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(host, port);
Console.WriteLine("Connected.");
s.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallBack, s);
}
public void Stop()
{
if (s != null)
{
s.Close();
s.Dispose();
s = null;
}
}
void ReceiveCallBack(IAsyncResult ar)
{
Socket s = ar as Socket;
if (s != null && s.Connected)
{
int rcvd = s.EndReceive(ar);
if (rcvd > 0)
{
s.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallBack, s);
return;
}
}
if(Disconnected!=null)
Disconnected(this, EventArgs.Empty);
}
}
这只是基本的 - 我不确定sql server会持续多长时间保持一个没有响应的套接字。也许添加一个计数 - 断开连接重新连接,看看它实际上是否真正脱离等等......
答案 1 :(得分:0)
听起来像Timer会为此目的而工作。带有线程睡眠的无限循环中的后台线程也可以工作,但我不喜欢无限循环中的任何东西。
见
这是检查连接的fxn
namespace answer1
{
using System.ComponentModel;
using System.Data.SqlClient;
internal class ConnectionCheck
{
private BackgroundWorker bw = new BackgroundWorker();
private void CheckConnection()
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
Console.WriteLine("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
CheckConnection();
System.Threading.Thread.Sleep(5000);
}
}
/// <summary>
/// This is the Main routine you call to execute the background thread
/// </summary>
public void RunBackgroundSQLCheck()
{
bw.DoWork += this.bw_DoWork;
bw.RunWorkerAsync();
}
}
}