I am accepting TCP clients using the below code:
TcpClient client = tcpListener.AcceptTcpClient();
Task.Factory.StartNew(() => Read_it(client, tcpPort)).ContinueWith(x =>
{
if (x.Exception != null)
{
x.Dispose();
}
}, TaskContinuationOptions.OnlyOnFaulted |
TaskContinuationOptions.OnlyOnRanToCompletion).ContinueWith(x =>
{
x.Dispose();
});
}
I have two questions.
Is it necessary to dispose tasks like this? Especially when the task itself has disposed code for the TcpClient and NetworkStream?
Is my code an acceptable way of disposing tasks that ran to completion or faulted? Or for example, does the Garbage Collector eventually clean up any task that has been completed one way or another? Maybe do I manually call Garbage Collector, say every 10 minutes or so?