0

I've met such a problem: my function takes a very long time to run. If a user runs that function by mistake he must wait until the function gets to the end. Is it possible to stop a function by clicking "Escape", for example? I just can't send anything to the function while it is running.

Thanks, Andrew.

Nigel B
  • 3,577
  • 3
  • 34
  • 52
Andrew
  • 3
  • 2
  • 2
    I suggest you look into the `BackgroundWorker` class. http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx – Kevin DiTraglia Aug 22 '13 at 14:55
  • http://stackoverflow.com/questions/5506457/start-stop-pause-and-continue-a-very-long-running-method – Habib Aug 22 '13 at 14:56
  • You need to use second thread for such long-running functions. Search for Task Parallel Library and RequestCancellationToken. http://msdn.microsoft.com/en-us/library/dd997396.aspx – VsMaX Aug 22 '13 at 14:56
  • http://stackoverflow.com/questions/1410602/how-do-set-a-timeout-for-a-method – David Brabant Aug 22 '13 at 14:58

3 Answers3

3

The wrong approach would be to run your method on a separate thread, and abort that thread when it is needed.

The right approach is to pass some marker to the method and method itself would check it from time to time, returning if the marker says that it should. You can use TPL with CancellationToken to do just that.

alex
  • 12,464
  • 3
  • 46
  • 67
-1

You can run the task on a different thread, and if the user wants to finish the task, then you might call yourThread.Stop() or yourThread.Abort()

Anyway, you should control your process before just killing it, that way it is safer.

Hope that helps!

NicoRiff
  • 4,803
  • 3
  • 25
  • 54
  • Thread.Abort is never, ever a suitable solution. What if the ongoing task has some cleanup it needs to do? Maybe it needs to roll back some changes like windows installer does. – Gusdor Aug 22 '13 at 15:24
-1

You should run your function in parallel, using a thread, a BackgroundWorker or the Task parallel library.

This will allow you to keep the user interface responsive and to cancel the background operation.

Alberto
  • 15,626
  • 9
  • 43
  • 56