5

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

Geo P
  • 754
  • 1
  • 5
  • 18
  • possible duplicate of [c# - abort the execution of a method if its taking too long to run](http://stackoverflow.com/questions/4768623/c-sharp-abort-the-execution-of-a-method-if-its-taking-too-long-to-run) – Kirk Woll May 30 '12 at 17:55
  • Execute method in other thread and when you need - kill it :) – Renatas M. May 30 '12 at 17:56
  • 1
    If you've got any I/O resource - a file handler, a db / web connection, the answer is to close that resource. – ControlAltDel May 30 '12 at 17:56
  • Are you running the method in a separate thread from the one where "specific event is raised"? Or you want to cancel method that synchronously runs on UI thread from the same thread? – Alexei Levenkov May 30 '12 at 18:06
  • 1
    @GeoP If this is on the UI thread, then you definitely need to use a cooperative cancellation model, as "killing" it would be even worse than normal :) – Reed Copsey May 30 '12 at 18:24

2 Answers2

7

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

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:

  • execute long-running methods on separate thread
  • use asynchronous execution of operations wherever possible.

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.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179