日期:2014-05-17  浏览次数:20966 次

C# C/S 异步通信问题

一下代码在Winform中运行正常,但是在console中,执行到DoBeginAcceptTcpClient的  listener.BeginAcceptTcpClient(new AsyncCallback(this.DoAcceptTcpClientCallback), listener);后系统就运行结束了,请问是什么原因

    public void Start()
        {
            Thread t = new Thread(new ThreadStart(this.BeginListen));
            t.Start();
        }

        private void BeginListen()
        {
            try
            {
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                TcpListener listener = new TcpListener(ip, Settings.Default.Port);
                listener.Start();
                Console.WriteLine("=====Socket文件服务开启=====");

                DoBeginAcceptTcpClient(listener);


            }
            catch (Exception ex)
            {
                Console.WriteLine("文件服务开启失败原因为:");
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// begin a new connection by asynchronous
        /// </summary>
        /// <param name="listener"></param>
        private void DoBeginAcceptTcpClient(TcpListener listener)
        {
            listener.BeginAcceptTcpClient(new AsyncCallback(this.DoAcceptTcpClientCallback), listener);
        }
        }


        private void DoAcceptTcpClientCallback(IAsyncResult ar)
        {

            try
            {
                TcpListener listener = ar.AsyncState as TcpListener;
                TcpClient tcpClient =&n