简体   繁体   中英

SSH.NET “Cannot access a disposed object”

I have recently been fiddling with the SSH.NET library and I've been searching/troubleshooting the disposed object error when trying to execute a second command. Here is my code:

private void statusBtn_Click(object sender, System.EventArgs e)
{
    Commands("status");
}

private void startBtn_Click(object sender, System.EventArgs e)
{
    Commands("start");
}

private void Commands(string cmd)
{
    using (sdtd_client)
    {
        sdtd_client.Connect();
        switch (cmd)
        {
            case "status":
                var status = sdtd_client.CreateCommand("7dtd.sh status Nom");
                string result = status.Execute();
                outputBox.AppendText(result);
            break;
            case "start":
                var start = sdtd_client.CreateCommand("uptime");
                string result_start = start.Execute();
                outputBox.AppendText(result_start);
            break;
            default:
                outputBox.AppendText("Unrecognized Command.");
            break;
        }
        sdtd_client.Disconnect();
    }
}

I realize "sdtd_client.Disconnect();" is disposing the connection, but even without using that, it still disposes.

How can I safely connect, execute, disconnect each time I run different commands?

Even if I opened the connection on application start and only disconnected on unload, every command executed will dispose the connection object.

Is there something obvious I am missing?

You haven't posted the declaration/initialisation of sdtd_client in your code, but the using (sdtd_client) block will dispose the object every time it leaves the block. I suspect you don't really want that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM