首页 文章

System.dll中出现未处理的'System.ObjectDisposedException'类型异常

提问于
浏览
1

在我的项目中,当我通过调试运行它时,经过一段时间后,它突然崩溃了 . 它没有在任何特殊时间或特定时期之后发生 . 它崩溃了,我不知道为什么?!

我收到了这条消息:

An unhandled exception of type 'System.ObjectDisposedException' occurred in System.dll
Additional information: Cannot access a disposed object.

及其图片,了解更多信息......

enter image description here

我正在使用vs 2013和C#win form ...

它是我的简单代码:

private void btnConnect_Click(object sender, EventArgs e)
    {
        Result = socketComponent.tcpConnect(Host, int.Parse(Port));
        if (Result == 0)
            MessageBox.Show("Connected"); 
    }

private void btnDisconnect_Click(object sender, EventArgs e)
{
    if (socketComponent != null)
    {
        socketComponent.tcpDisconnect();

        socketComponent.Dispose();
        MessageBox.Show("DisConnected"); 
    }

}

单击“打开btnDisconnect”后突然发生这种情况 . 也许在第二次点击或更多....

谢谢你的帮助......

1 回答

  • 0

    我的猜测是,您应该像这样更改代码:

    private void btnDisconnect_Click(object sender, EventArgs e)
    {
        if (socketComponent != null)
        {
            socketComponent.tcpDisconnect();
    
            socketComponent.Dispose();
    
            // set to null!
            socketComponent = null;
            //
    
            MessageBox.Show("DisConnected"); 
        }
    }
    

    因为否则,再次单击"btnDisconnect"将再次调用 Dispose ,这通常是在已经处置的对象上不允许的 . 因此,例外 .

相关问题