Real-Serious-Games / C-Sharp-Promise

Promises library for C# for management of asynchronous operations.
MIT License
1.2k stars 149 forks source link

Cancelling promises #75

Closed Mazhug closed 6 years ago

Mazhug commented 6 years ago

Hello!

First off, thank you for this awesome library. It is very useful and well written.

My question is, are there plans to add functionality to cancel promises? It would be a very useful feature to handle cases where a connection is lost/a user logs out/the user navigates to another screen and the promised resource is no longer required.

If not, do you have a best practice guideline in handling those cases when using promises for async operations?

Thank you very much, -Nic

ashleydavis commented 6 years ago

One way you can easily abort a promise is by creating a timeout.

You can see an example in my article. Search for 'timeout'.

One could easily imagine adding something like a 'timeout' that aborts a promise with a CancelException if the user cancels the promise.

The problem with cancellation is that the promise library is not in control of the async operation that it wraps up, so therefore it cannot cancel that operation. So adding cancellation to the promise library is not something that's doable in my option.

However you do control the async operation that the promise wraps, it's your code after all that is running, so you can make it return early or abort with an exception. In fact this is what timeout does, in working together with Promise.Race it throws an exception to abort the promise chain when a certain period of time expires.