• 快速检测数据库是否连接上(与其它主机连接)


    在连接主机数据库的时候如果连接不上,会等待很长时间。其实并不是连接数据库慢,而是连接到数据库所在的主机慢。

    View Code
    1 using System;
    2  using System.Collections.Generic;
    3  using System.Linq;
    4 using System.Text;
    5
    6 using System.Net.Sockets;
    7 using System.Threading;
    8
    9 namespace Commone
    10 {
    11 /// <summary>
    12 /// 网络端口状态检查类
    13 /// </summary>
    14 public class NetPortOp
    15 {
    16 private static bool IsConnectionSuccessful = false;
    17 private static Exception socketexception;
    18 private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
    19
    20 /// <summary>
    21 /// 验证连接指定主机的端口
    22 /// </summary>
    23 /// <param name="host">主机IP或名称</param>
    24 /// <param name="port">端口号</param>
    25 /// <param name="timeoutMSec">超时时长(毫秒)</param>
    26 /// <returns>bool</returns>
    27 public static bool ConnValidate(string host, int port, int timeoutMSec)
    28 {
    29 bool ret = false;
    30
    31 TimeoutObject.Reset();
    32 socketexception = null;
    33
    34 TcpClient tcpclient = new TcpClient();
    35
    36 tcpclient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpclient);
    37 if (TimeoutObject.WaitOne(timeoutMSec, false))
    38 {
    39 if (IsConnectionSuccessful)
    40 {
    41 ret = true;
    42 tcpclient.Client.Close();
    43 }
    44 else
    45 {
    46 //不用抛出异常,根据ret判断连接成功与否
    47 //throw socketexception;
    48 }
    49 }
    50 else
    51 {
    52 //不用抛出异常,根据ret判断连接成功与否
    53 //throw new TimeoutException("TimeOut Exception");
    54 }
    55
    56 tcpclient.Close();
    57 return ret;
    58 }
    59
    60 private static void CallBackMethod(IAsyncResult asyncresult)
    61 {
    62 try
    63 {
    64 IsConnectionSuccessful = false;
    65 TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
    66
    67 if (tcpclient.Client != null)
    68 {
    69 tcpclient.EndConnect(asyncresult);
    70 IsConnectionSuccessful = true;
    71 }
    72 }
    73 catch (Exception ex)
    74 {
    75 IsConnectionSuccessful = false;
    76 socketexception = ex;
    77 }
    78 finally
    79 {
    80 TimeoutObject.Set();
    81 }
    82 }
    83 }
    84 }
    bool b = Commone.NetPortOp.ConnValidate("192.168.1.119", 1433, 1000);
    //连接上返回true,否则返回false。
    
    
  • 相关阅读:
    高低 接口
    算法
    一致连续性定理
    Brouwer fixed-point theorem
    minimum viable product
    Python星号*与**用法分析 What does ** (double star/asterisk) and * (star/asterisk) do for parameters? 必选参数 默认参数 可变参数 关键字参数
    zabbix 添加主机接口
    zabbix 添加主机接口
    zabbix 添加主机成功失败判断
    zabbix 添加主机成功失败判断
  • 原文地址:https://www.cnblogs.com/yalong_xiang/p/1984932.html
Copyright © 2020-2023  润新知