As the title says, I call a method which starts to load from a database. If a specific event is raised, I would like to prematurely exit that method without waiting for it to finish loading.
Edit: The method in question runs on the UI thread
As the title says, I call a method which starts to load from a database. If a specific event is raised, I would like to prematurely exit that method without waiting for it to finish loading.
Edit: The method in question runs on the UI thread
There is no way to (cleanly) destructively cancel a method from outside of that method.
Cancellation in the .NET Framework is typically a cooperative model. This means you're event would request a cancellation, and the method would, in turn, occasionally check for whether it should cancel and then exit cleanly.
This is handled via the CancellationToken
and CancellationTokenSource
types within the framework. For details, see the topic about Cancellation on MSDN.
If you execute your long-running method on UI thread than there is pretty much nothing built in that can help to stop it. Also UI thread will not be able to listen to any events (as it is blocked on the method execution).
Your options to make UI responsive and operation cancel-able:
To cancel - you may be able to cancel some operations by terminating/closing connection/file the operation is performed on. Note that most IO operations do not guarantee that such action will immediately terminate the method.