C#'无法访问已处置的对象。对象名称:“ SslStream”。”

时间:2018-11-03 04:22:15

标签: c#

我的问题标题中的异常被抛出return allMessages;在下面的代码中。我不明白这是因为该行代码仍在using(var sslStream ...)语句内,因此在执行该代码时,不应处置SslStream对象。

public static List<Message> FetchAllMessages(string hostname, int port, string username, string password, string proxyIp, int proxyPort)
{
    // The client disconnects from the server when being disposed
    using (Pop3Client client = new Pop3Client())
    {
        var proxyClient = new HttpProxyClient(proxyIp, proxyPort);
        using (var sslStream = new SslStream(proxyClient.CreateConnection(hostname, port).GetStream()))
        {
            sslStream.AuthenticateAsClient(hostname);
            client.Connect(sslStream);
            // Authenticate ourselves towards the server
            client.Authenticate(username, password);
            // Get the number of messages in the inbox
            int messageCount = client.GetMessageCount();

            // We want to download all messages
            List<Message> allMessages = new List<Message>(messageCount);

            // Messages are numbered in the interval: [1, messageCount]
            // Ergo: message numbers are 1-based.
            // Most servers give the latest message the highest number
            for (int i = messageCount; i > 0; i--)
            {
                allMessages.Add(client.GetMessage(i));
            }
                            // Now return the fetched messages
            return allMessages;
        }
    }
}

更新:

在返回allMessages时设置一个断点;并悬停在sslStream对象上,则不会对其进行处理。

当我删除using语句并只声明var sslStream时,它可以工作,但是我认为如果没有它,伸缩性就不会很好。

1 个答案:

答案 0 :(得分:1)

因此,我对原因没有真正的解释,但是重新启动计算机可以解决问题,这样做之后代码可以正常运行...