How to delete a task correctly

Am I somehow deleting this task or self-developed?

Task.Factory.StartNew(() => { DoSomeJob(); }, TaskCreationOptions.LongRunning); 

or is it better to use it as

 var t = Task.Factory.StartNew(() => { DoSomeJob(); }, TaskCreationOptions.LongRunning); 

and somehow delete / reset t later?

Thanks!

+4
source share
4 answers

you do not need to delete it, it will be deleted in the end.

+3
source

If you mean, can you cancel it or interrupt it or in some other way stop it from starting until it is completed; no, not really (like it is currently). You will need to create a source of the cancellation token, pass the token to the Task, and then the method launched in the task must periodically check that it is not canceled.

What you can do is wait a while and cancel this wait operation. This will allow you to continue with the next task that you need to complete. Please note: if you do this without adding the work that I mentioned above, where the method in the task itself checks for deletion, then the method will still be completed before completion, you will simply stop waiting for it earlier.

Related Links

If you are just worried about cleaning up the resources that the task uses when they are running, you need not worry. Everything will be processed automatically.

Related Links

+3
source

If you want to try and get rid of it yourself, you need to be careful. If it is still operational, you will get this exception:

 A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled) 

So, it is better to use your first example.

+2
source

Garbage collection will handle the cleanup for you, you don't need to keep the t link.

+1
source

Source: https://habr.com/ru/post/1439394/


All Articles