当前位置: 代码迷 >> C# >> WPF Socket编程,无法访问已释放的对象异常,求帮忙
  详细解决方案

WPF Socket编程,无法访问已释放的对象异常,求帮忙

热度:29   发布时间:2016-05-05 04:09:23.0
WPF Socket编程,无法访问已释放的对象错误,求帮忙
WPF Socket编程,我有两个按钮,一个连接,一个关闭,点完连接按钮,再点关闭,程序提示错误: 无法访问已释放的对象;debug调试异常出现在接收的回调函数里,我关闭函数这么写的,大家帮忙看看有什么问题吗?
连接函数:
private void btnConnectServer_Click(object sender, RoutedEventArgs e)
        {
            m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(txtIPAddress.Text), 1024);

            try
            {
                m_clientSocket.Connect(remoteEndPoint);
                if (m_clientSocket.Connected)
                {
                    m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);

                    btnConnectServer.IsEnabled = false;
                    btnDisconnectServer.IsEnabled = true;

                    this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client connect server success.");

                    m_bTCPIPConnect = true;
                }
            }
            catch (Exception)
            {
                this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client connect server fail.");
                m_clientSocket = null;
            }
        }
关闭函数:
private void btnDisconnectServer_Click(object sender, RoutedEventArgs e)
{
            if (m_clientSocket != null)
            {
                m_clientSocket.Close();

                btnConnectServer.IsEnabled = true;
                btnDisconnectServer.IsEnabled = false;
                btnSendMsg.IsEnabled = false;

                this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Client disconnected.");

                m_bTCPIPConnect = false;
            }
 }

回调函数:
private void ReceiveCallBack(IAsyncResult ar)
        {
            try
            {
                int REnd = m_clientSocket.EndReceive(ar);
                string strReceiveData = Encoding.Default.GetString(m_receiveBuffer, 0, REnd);
                
                m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);              
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

debug感觉红色部分出错,请大家帮忙看看,先谢谢了
------解决思路----------------------
加个判断if (m_clientSocket.Connected)试试
------解决思路----------------------
  int REnd = m_clientSocket.EndReceive(ar);
if(REnd>0)
{
                    string strReceiveData = Encoding.Default.GetString(m_receiveBuffer, 0, REnd);
                
                    m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);    
}else
{
   与服务端断开连接   
}


只是关闭Socket,为什么接收数据的回调函数会执行呢 这是因为连接断开后 m_clientSocket.BeginReceive 会执行一个返回为0字节的数据,所以上面做的就是那种判断
  相关解决方案