Test whether the database server is available

Source: Internet
Author: User

The setting of Connect Timeout in the SQL connection string is invalid and can only be determined through Socket.

The Code is as follows:

/// <Summary>
/// Test whether the database server is available
/// </Summary>
/// <Param name = "ip"> Server IP </param>
/// <Param name = "port"> server port, usually 1433 </param>
/// <Param name = "timemout"> set the timeout time in milliseconds </param>
/// <Returns> If the database is available, true is returned; otherwise, false is returned. </returns>
Static bool TestConn (string ip, int port, int timemout)
{
Using (TcpClient client = new TcpClient ())
{

ManualResetEvent mre = new ManualResetEvent (false );
Client. BeginConnect (ip, port, delegate (IAsyncResult res)
{
If (client. Connected)
{
Mre. Set ();
Console. WriteLine ("123 ");
}
}, Null );
ThreadPool. QueueUserWorkItem (delegate (object obj) {Thread. Sleep (timemout); mre. Set ();});
Mre. WaitOne ();
If (! Client. Connected)
{
Return false;
}
Return true;
}
}

Test code:

DateTime begin = DateTime. Now;
Console. WriteLine (TestConn ("192.168.1.99", 1433,200 0 ));
Console. WriteLine (DateTime. Now. Subtract (begin). TotalSeconds );

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.