Whilst searching the reason for a await Task.Run( ... );
not being interrupted when the CancellationToken
was cancelled, I've found this SO post where I've learned that it doesn't work as straight forward as it seemed in the beginning.
Having that in mind, I could I force a stop / cancel in a given task with a CancellationToken
?
In the same post, I've read that in some cases, an if
checking if the given CancellationToken
has been cancelled would make the effect I'm searching for, the problem is: I don't have a cycle of any kind in there and - the main reason - I'm only calling a blocking method inside the Task.Run( ... );
(hence the fact of using a Task
to not block the UI).
Other problem with this is that that Task
is inside a click event, so the user may click again and, due to the Task
not being cancelled, I'm afraid that a variable might get caught in the middle, screwing up the app.
Basically, this is what is happening:
- User gets there.
- User inputs the requested info.
- An redirect occurs.
- The user is back.
- The task starts running. The user can cancel it anytime.
If the user waits for the operation to finish
- The task ran to completion. The result is stored into a var.
- The var is processed.
- The result is shown to the user.
If the user does not wait for the operation to finish and makes the request again
- The user cancels the operation.
- The user goes trough the steps 1, 2, 3 and 4 again.
- The task starts running. The user can cancel it anytime. There are now 2 task running the same method waiting for a result.
- From now on, the first task might return the result whilst the second task, the one that should get the result, might return other value other than the expected one. ( I might be wrong here )
- The end of the world is near...
How should I manage this? I'm only using the Task.Run( ... )
to avoid the UI being blocked.