Threading.Tasks Eliminating the meaning of the problem

I would like to integrate the use of a class into my application Tasks

, because this is the one that I know is doing my requests, since I only need to start one very simple asynchronous operation to call a safe WinAPI method, and then if I use a background worker, which would be a very huge solution and just insane in my opinion just to execute one instruction in this way:

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

      

I need to execute this instruction many times a minute (for example 100), but I cannot wait for the asynchronous operation to complete and destroy the object using the method Wait

, because even if the current one is Task

alive, my intention is to start another instance of Task

the same operation and letting the old task still work, so I don't know if the GarbageCollector

objects will be automatically deleted Task

when each task ends or do I need to dispose of each of them can be used with the method Dispose

?, in which case I am very lost because I don't know. like in this case I mentioned.

I'm a little confused about this method, I tried for curiosity this very simple test below, every time I execute this loop, the memory grows by about 20mb in my case, and I don't see the consumption as all .NET experts know that memory consumption indicators for a vb.net application can be very inefficient, so I still agree with this little test below:

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

      

Please someone out of my doubts.

+3


source to share


2 answers


Task.Dispose

exists to remove the internal wait descriptor, which is used if you are doing blocking operations on Task

(like calling Wait()

). If you don't, there is no point in calling Dispose

.



When executing tasks, it is generally a good idea not to call Dispose

unless you have this very specific scenario and is causing performance issues. If there is a wait handle and you don't Dispose

, there is no harm - it will be picked up by the GC at some point.

+6


source


The GC will always be able to clean up resources that are no longer available through your application. You don't need to do anything special to do this. Disposal is very explicitly intended for unmanaged resources that are not within the purview of the GC. Tasks, in particular, do not need to be deleted. You don't have to worry about cleaning them up after starting them.



Of course, just because the GC can clean up managed resources doesn't necessarily mean it will do it right away. He can do this whenever needed. You must let him optimize you; trying to get it to act will in most cases only ever cause you problems.

+4


source







All Articles