3

I've put some code into a background task as following:

private async void WriteToAuditLog(object sender, WriteToAuditLogAction e)
    {
        var auditTuple = new Tuple<DateTime, string>(e.Time, e.Message);
        var backgroundTask = Task.Factory.StartNew(() => { WorkerOperationForWriteToAuditLog(auditTuple); });
        await backgroundTask;
        ***backgroundTask.Dispose();***

    }

Is it safe to call dispose on the task after invoking await? As far as I understand, the dispose line will be executed after the task has been completed and the control is returned to the UI thread, right? So, I no longer have need of the task and may safely Dispose it, am I correct?

Cod Fish
  • 917
  • 1
  • 8
  • 37
  • Are you sure `Task` is Disposable? – Jamiec Mar 05 '18 at 09:07
  • @Jamiec It has a Dispose() method with the comments: [Releases all resources used by the current instance of the System.Threading.Tasks.Task class.] Also, it implements IDisposable: [public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable] – Cod Fish Mar 05 '18 at 09:09
  • See [here](https://stackoverflow.com/questions/3734280/is-it-considered-acceptable-to-not-call-dispose-on-a-tpl-task-object) – Alex Seleznyov Mar 05 '18 at 09:12
  • Yes - my bad I was looking at `Task` which of course inherits from `Task` and gets the `IDisposabe` from there – Jamiec Mar 05 '18 at 09:14
  • 1
    It's safe, but you don't really need to do that. Also, if task fails - your `Dispose` will not be called (again - you don't need to call it anyway, but if you insist - at least do that correctly). – Evk Mar 05 '18 at 09:15
  • 1
    https://blogs.msdn.microsoft.com/pfxteam/2012/03/25/do-i-need-to-dispose-of-tasks/ – Marco Mar 05 '18 at 09:16
  • @Evk Can you please guide me a bit for the correct way of disposing a task, also when it fails, so that it will be disposed for all scenarios - both success and failure? I insist, cause we do have performance / memory issues in our system (not necessarily due to not disposing tasks) , so I wish to clean up any resources that I can when I know I don't need them anymore. – Cod Fish Mar 05 '18 at 09:34
  • 1
    Then just wrap it in using statement. But you need to read links provided in comments, because then you will know disposing task will do absolutely nothing except in very specific cases (not this one), so cannot improve your perfomance. – Evk Mar 05 '18 at 09:37

0 Answers0