Search code examples
c#multithreadingusing

Using Block with Threading


I'm reasonably experienced with C#, however I've never come across this problem before, and I was wondering if any more experienced C# Developers know what to do in this situation. Here's the code for the method in question: (the problem is explained after the block of code)

public void ConnectToRemoteServer() 
{
    Console.WriteLine("Attempting to connect to " + config.GetString(ConfigParams.MasterServerIp) + ":" + config.GetString(ConfigParams.MasterServerPort));
    TcpClient client = new TcpClient();
    IPEndPoint address = new IPEndPoint(IPAddress.Parse(config.GetString(ConfigParams.MasterServerIp)), config.GetInt(ConfigParams.MasterServerPort));
    Console.WriteLine("Connecting...");
    //Begin asynchronous sever communication
    if (this.autoTask == null)
    {
        communicator = new CommunicationListener(client, config, address);
    }
    else
    {
        communicator = new CommunicationListener(client, config, address, this.autoTask);
    }
    Thread communicationThread = new Thread(new ThreadStart(communicator.Start));
    communicationThread.Start();
}

The part that I'm wondering about is if I should be using a using statement in this block of code. I know that TcpClient implements the interface IDisposable, and as such should be encapsulated in a using statement, however, in this case, a new thread is started that uses the TcpClient, and as such the end of the using block will be reached before the TcpClient is done being used. So should I be using the using statement here?


Solution

  • The general rule of thumb is that if its IDisposable then you should dispose of that object.

    A using block gives you a nice easy way to do that, but since your TCPClient will persist outside of this method, then it cant be used in this case.

    If you really wanted to write nice code then should; declare your TCPClient within your class, have your class implement IDisposable, dispose of your TCPClient within your new Dispose method. (and maybe do something about ending your thread).

    That way you can wrap your class within using block.