I want to be able to cancel reading from a database or http request instantly when our app is reading some data from either and the user hits the cancel button. Neither call is immediately cancellable, even for the async versions of the calls.
What if I set the code to end the task as soon as the next database/http call completes? And then forget about that task and continue on in my app? The one downside I can see is if the task does not complete before the user exists the app.
Update: JPVenson provided a great solution for doing this right for http and ADO.NET. However, we also at times do this making calles to the Salesforce API which as best as I can figure out, has no cancel mechanism. So the problem remains for that case.
On a cancel I don't need what is being returned so from my apps point of view, I'm fine forgetting about the task. Is there any down side to doing this?
how would you "kill" a task? AFAIK you can only "kill" Threads but not tasks as they have no such mechanism.
When using the Standard TaskScheduler, Tasks will be enqueued as an ThreadPoolItem and in the case that you stop your application, all thoese ThreadPool Thread will be killed including all remanding/still running Tasks.
For the Headline: It truly depends on the kind of Task but in general you always want to observe the result of any of your Tasks for at least Logging purposes. If you do not observe and also handle potential exceptions that are thrown by the task, you risk a "corrupted state" of your application where the task might crash in a way you did not anticipate before and therefore altering data within your app that does not make sense.
So yes, it is highly recommended that you handle all of your tasks at very least for logging and error correction/observation.
For Canceling an HTTP call: WebClient: how to cancel a long running HTTP request?
For Canceling an SQL Command: This is a way other story and heavily depends on the ORM you are using - EF Cancelling an Entity Framework Query - Ado.Net https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.cancel?view=netframework-4.8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With