1

我的 c# 应用程序中有这段代码:

private bool connected 
public void ChangeStatusa()
{
     if(connected)
     {
       label1.Text="Connected"
     }else{
      label1.Text="Connected"
     }
}

我想在 sql server 断开连接时自动执行此代码,

我想在后台完成这项工作而不影响我的应用程序性能。

本质上,我想在我的应用程序中创建一个系统,负责检查 sql server 连接,并在连接丢失时自动更改状态。

4

2 回答 2

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 会保留一个没有响应的套接字多久。也许添加一个计数 - 在断开连接时重新连接,看看它是否真的是一个真正的断开连接等等......

于 2013-09-09T21:16:59.263 回答
0

听起来 Timer 可以用于此目的。带有线程睡眠的无限循环中的后台线程也可以工作,但我不喜欢无限循环中的任何东西。

C# 后台线程

这是一个检查您的连接的 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();
        }
    }
}
于 2013-09-09T20:35:58.673 回答