有一段网络检测的代码,在网络出现故障时,检测会变的很慢。而且这里还需要循环检测,所以一旦出现异常,程序就会假死了,查了很多资料也没理出个头绪,希望大家帮个忙,下面是代码
                Socket s = null;
                NetworkStream ns = null;
                StreamWriter sw = null;
                try 
                {
                    s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 200);
                    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 200);
                    s.Connect(pIPOrCom, 9100);//就是在这块,检测的时候需要很长时间
                } 
                catch (Exception ex) 
                {
                    tag = true;
                    class11.pState1.BackColor = Color.Red;
                    class11.pState1.Text = "连接失败";
                    System.Util.MyLog.Log(ex);
                }这是主要的地方,其中在finally 中已经将       s.Close();

解决方案 »

  1.   

    class Program
     {
         static void Main(string[] args)
         {
    ...
             AsyncTest test = new AsyncTest();
             TestHandler dele = test.connectTest;
     
           dele.BeginInvoke(GetResultCallBack, null);
             ...
       }
      //回调方法
       static void GetResultCallBack(IAsyncResult asyncResult)
       {
    string val=null;
            AsyncResult result = (AsyncResult)asyncResult;
            TestHandler.salDel = (TestHandler)result.AsyncDelegate;
           try
            {           val = salDel.EndInvoke(asyncResult);
                Console.WriteLine(val);
           }
           catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }public delegate void TestHandler(); public class AsyncTest
    {
        public string connectTest()
        {你的代码,返回链接信息(成功,不成功)
            try
    {
    ....
    }
    catch
    {...
    }
        }
    }
    不知道行不行,异常很少用,不是太熟练
      

  2.   

    这是一个异步的框架,跟你使用什么方法没有关系,就是.net处理异步的一个基本思路,你的方法写到connecttest里面,他就会异步开启你的方法来进行处理,你使用什么ip地址没有关系,如果是你说的是传参的话,begininvoke是支持传参的
      

  3.   

    今天我找了一个类,在s.Connect(pIPOrCom, 9100)之前
    用TimeOutSocket.Connect(remoteEP, 1000)调用,感觉效果还可以
    不知道大家有什么好的建议?class TimeOutSocket
        {
            private static bool IsConnectionSuccessful = false;
            private static Exception socketexception;
            private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);
            public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
            {
                TimeoutObject.Reset();
                socketexception = null;
                string serverip = Convert.ToString(remoteEndPoint.Address);
                int serverport = remoteEndPoint.Port;
                TcpClient tcpclient = new TcpClient();
                try
                {
                    tcpclient.BeginConnect(serverip, serverport,
                        new AsyncCallback(CallBackMethod), tcpclient);
                    if (TimeoutObject.WaitOne(timeoutMSec, false))
                    {
                        if (IsConnectionSuccessful)
                        {
                            return tcpclient;
                        }
                        else
                        {
                            throw socketexception;
                        }
                    }
                    else
                    {
                        tcpclient.Close();
                        throw new TimeoutException("TimeOut Exception");
                    }
                }
                finally
                {
                    tcpclient.Close();
                }
            }        private static void CallBackMethod(IAsyncResult asyncresult)
            {
                try
                {
                    IsConnectionSuccessful = false;
                    TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
                    if (tcpclient.Client != null)
                    {
                        tcpclient.EndConnect(asyncresult);
                        IsConnectionSuccessful = true;
                    }
                }
                catch (Exception ex)
                {
                    IsConnectionSuccessful = false;
                    socketexception = ex;
                }
                finally
                {
                    TimeoutObject.Set();
                }
            }