ElektroStudios
ElektroStudios

Reputation: 20464

Threading.Tasks Dispose meaning issue

I would like to integrate in my application the Tasks Class usage because is the one that I know accomplish my requeriments as I only need to launch one very simple asynchronous operation to call a safe WinAPI method, then if I use a background worker that would be a very huge solution and just insane in my opinnion only to run one instruction in this way:

Task.Factory.StartNew(Sub() NativeMethods.SomeWrapper)

I need to execute that instruction much times per minute (like 100), but I can't wait for the asynchronous operation to finish and dispose the object using the Wait method because even if the current Task is alive my intention is to launch another Task instance of the same operation and let the old task still working, so I don't know whether the GarbageCollector will dispose my Task objects automatically when each task finishes or I need to dispose each one manualy using the Dispose method?, in that case I'm very lost 'cause I don't know how to in this circunstances that I mentioned.

I'm a little bit confused with that method, I've tried for curiosity this very simple test below, each time that I execute this loop the memory increases around 20 mb in my case and I don't see that consumption gets disposed never, anyways, I'm not a profiler experto but as all the .NET experts knows the memory consumption indicators for a vb.net app could be very inefficient, so I still consufe even with this little test below:

For x As Integer = 0 To 99999
    Task.Factory.StartNew(Sub() NativeSafeMethods.SomeSafeWrapper)
Next

Please someone get me out of doubt.

Upvotes: 3

Views: 85

Answers (2)

Cory Nelson
Cory Nelson

Reputation: 30001

Task.Dispose exists to dispose of an internal wait handle that is used if you perform blocking operations on the Task (like calling Wait()). If you don't do that, there's no point in calling Dispose.

With tasks, it is generally recommended to not call Dispose unless you've got that very specific scenario and it is causing performance problems. If there's a wait handle and you don't Dispose, there's no harm -- it will be picked up by the GC at some point.

Upvotes: 6

Servy
Servy

Reputation: 203834

The GC will always be able to clean up resources that are no longer accessible through your application. You never need to do anything special to enable this. Disposal is very explicitly for unmanaged resources that aren't within the GC's realm of responsibility. Tasks, specifically, don't need to be disposed. You don't need to worry about cleaning them up after you start them.

Of course, just because the GC can clean up managed resources doesn't necessarily mean it will do so right away. It's free to do so whenever it feels the need to do so. You should let it optimize itself; trying to force it to act will, in most cases, only ever cause you problems.

Upvotes: 4

Related Questions