jnovo
jnovo

Reputation: 5779

Are there any downsides to keeping Task objects around long after completed?

I've found myself growing the habit of keeping the Task objects well beyond their completion as result containers.

So far I haven't identified any drawbacks and I find the code clearer than having separate variables to store the result after the tasks are completed.

A couple usage examples follow. Although I don't think it is really relevant, they have been though as part of View Models in MVVM applications. (Please note that this is not actual working code, I only try to outline the pattern.)

Task disposal is not the topic here, since I could dispose them later and anyways, it seems not necessary in these cases, as stated in the Do I need to dispose of Tasks? post from Parallel Programming with .NET MSDN Blog:

No. Don’t bother disposing of your tasks, not unless performance or scalability testing reveals that you need to dispose of them based on your usage patterns in order to meet your performance goals. If you do find a need to dispose of them, only do so when it’s easy to do so, namely when you already have a point in your code where you’re 100% sure that they’re completed and that no one else is using them.

My concerns are the following:

  1. Is this a good usage pattern?
  2. Are there any drawbacks or pitfalls in it? (e.g. memory leaks, potential deadlocks, locked pool resources, etc.)
  3. Should I, instead, unwrap the results from the tasks and store those directly (thus, in my opinion, increasing the code complexity)?

Upvotes: 4

Views: 112

Answers (1)

i3arnon
i3arnon

Reputation: 116558

  1. If it results in cleaner and clearer code for you, then yes it's a good pattern.
  2. The only real potential drawback is that these task don't get collected by the Garbage Collector. As long as you're using this pattern a few times and not thousands or millions of times that probably will never be a problem for you* (There's no fear of deadlocks or thread pool resources because a completed task is just that, completed. It will never have another thread processing it because tasks are not reusable).
  3. As long as memory doesn't become an issue, there's no reason to do that.

* Another drawback is that if you await a faulted task multiple times you would get the exception thrown each time. This may be problematic, but it depends on your specific exception handling.

Upvotes: 3

Related Questions