Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manually end a method call which is currently running?

Tags:

c#

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

like image 556
Geo P Avatar asked May 30 '12 17:05

Geo P


People also ask

How do you exit a run method in Java?

exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++.

How do you break a function?

Using return is the easiest way to exit a function. You can use return by itself or even return a value.

What does system Exit 0 do in Java?

exit with status code 0 is normal and others are abnormal exits. Note that this is only a “good practice” and is not a strict rule that the compiler would care about. Also, it's worth noting when we invoke a Java program from the command-line that the status code is taken into account.


2 Answers

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.

like image 179
Reed Copsey Avatar answered Oct 12 '22 14:10

Reed Copsey


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.

like image 30
Alexei Levenkov Avatar answered Oct 12 '22 13:10

Alexei Levenkov