2

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.

  1. Is it necessary to dispose tasks like this? Especially when the task itself has disposed code for the TcpClient and NetworkStream?

  2. 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?

Florian
  • 1,019
  • 6
  • 22
Ahmet
  • 33
  • 4
  • 5
    https://devblogs.microsoft.com/pfxteam/do-i-need-to-dispose-of-tasks/ – Johnathan Barclay Jan 12 '23 at 10:32
  • I've answered similar question before - [see here](https://stackoverflow.com/q/61919499/2501279) – Guru Stron Jan 12 '23 at 10:54
  • "do I manually call Garbage Collector..." - almost always, if you're asking such a question, the answer is no. You don't need to "help" the garbage collector, per se. If there are GC issues, they're due to objects living longer than they need to and the fix is to *resolve the lifetime issues*, not run the GC more often. – Damien_The_Unbeliever Jan 13 '23 at 08:02

0 Answers0