Удаление TcpClient при наличии ссылки на NetworkStream - PullRequest
1 голос
/ 07 января 2012

Скажите, у меня есть следующий код:

public static Client Connect(string hostname, int port, bool useSsl)
{
    TcpClient tcpClient = new TcpClient(hostname, port);
    if (!useSsl)
    {
        return new Client(tcpClient.GetStream());
    }
    SslStream sslStream = new SslStream(tcpClient.GetStream());
    sslStream.AuthenticateAsClient(hostname);
    return new Client(sslStream);
}

Когда я компилирую это, Code Analysis говорит мне, что я должен удалить tcpClient до того, как ссылка выйдет из области видимости. Проблема в том, что мне нужно использовать экземпляр базового потока дальше, и я не могу разместить здесь tcpClient. В то же время я не хочу хранить ссылку на tcpClient где-то для последующей утилизации, так как мне нужен только поток. Какое здесь правильное решение? Спасибо.

Ответы [ 2 ]

1 голос
/ 07 января 2012
public class Client : IDisposable
{
    private TcpClient tcpClient = null;

    public Client(string hostname, int port, bool useSsl) // c'tor
    {
        tcpClient = new TcpClient(hostname, port);

        if (!useSsl)
        {
            Init(tcpClient.GetStream());
            return;
        }

        SslStream sslStream = new SslStream(tcpClient.GetStream());
        sslStream.AuthenticateAsClient(hostname);

        Init(sslStream);            
    }

    private void Init(Stream stream)
    {
        // bla bla bla
    }

    public void Dispose()
    {  
        // this implementation of Dispose is potentially faulty (it is for illustrative purposes only)
        // http://msdn.microsoft.com/en-us/library/ms244737%28v=vs.80%29.aspx

        if( tcpClient != null ) {
            tcpClient.Close();
            tcpClient = null;
        }
    }
}
0 голосов
/ 07 января 2012

вы можете сделать это двумя способами .. 1. передать переменную по ссылке или 2. объявить приватную переменную вверху как SslStream sslStream = null; есть это

SslStream sslStream = new SslStream(tcpClient.GetStream()); 

изменить его или метод читать следующим образом.

public static SSLStream Connect(ref string hostname, ref int port, bool useSsl) 
{     
   TcpClient tcpClient = new TcpClient(hostname, port);
   if (!useSsl) 
   {
      return new Client(tcpClient.GetStream());
   }
   sslStream = new SslStream(tcpClient.GetStream()); // or the ref sslStream 
   sslStream.AuthenticateAsClient(hostname);
   tcpClient = null; or if implements IDisposable then do this
   if (tcpClient != null)
   {
      ((IDisposable)tcpClient).Dispose();
   }
   return sslStream; //if yo
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...