c# - Using Block with Threading -


i'm reasonably experienced c#, i've never come across problem before, , wondering if more experienced c# developers know in situation. here's code method in question: (the problem explained after block of code)

public void connecttoremoteserver()  {     console.writeline("attempting connect " + 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 i'm wondering if should using using statement in block of code. know tcpclient implements interface idisposable, , such should encapsulated in using statement, however, in case, new thread started uses tcpclient, , such end of using block reached before tcpclient done being used. should using using statement here?

the general rule of thumb if idisposable should dispose of object.

a using block gives nice easy way that, since tcpclient persist outside of method, cant used in case.

if wanted write nice code should; declare tcpclient within class, have class implement idisposable, dispose of tcpclient within new dispose method. (and maybe ending thread).

that way can wrap class within using block.


Comments