Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 480
ElektroStudios Avatar asked Sep 02 '26 04:09

ElektroStudios


1 Answers

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.

like image 152
Cory Nelson Avatar answered Sep 04 '26 20:09

Cory Nelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!