0

I have a simple UI that has two buttons 'Start' and 'Stop'. When user clicks 'Start' I have to perform a lengthy operation so I launch a worker thread to keep UI responsive. Now if user clicks Stop I need to stop the operation asap.

  1. One way to implement this is that the worker thread function checks for a bool bStop = false every second and if user clicks Stop we set bStop to true from the Stop button handler and the worker thread stops the current operation.

  2. Another way is to kill the thread using its handle.

Is there any better ways to do it?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Coder777
  • 985
  • 2
  • 9
  • 15
  • Second way Not recommended. Who knows what are you doing in the loop. If it remains half-complete, you will get lots of bugs. By loop, I mean that lengthy operation you've mentioned – mangusta Feb 23 '14 at 04:41
  • 1
    *Which* language/environment? Make sure this is readily reflected in the question and tags. – user2864740 Feb 23 '14 at 04:59
  • @user2864740, My questions is not bound to language. I just want to know best known practice followed. – Coder777 Feb 23 '14 at 05:44
  • @Coder777 Well, that's nonsense. Because the approaches available (much less the recommend approaches) are directly tied to a particular environment. For instance, it might be best to both use a flag and "signal" a thread - but when, where, and why? That's the actually important stuff! – user2864740 Feb 23 '14 at 05:49

2 Answers2

0

You can have a look at the new Cancel functionality via TPL.

http://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx

rajibdotnet
  • 1,498
  • 2
  • 17
  • 29
0

It depends on your environment, @Coder777.

In general, job cancellation requires the job to be programmed to accept a cancellation request and clean-up appropriately to avoid partial failure states. In very few environments is it safe to simply kill the thread (these environments have been coded specifically to handle thread termination in an orderly fashion).

If the job is non-blocking, a flag can be checked at one or more stages within the job to determine if the job should be cancelled; and, gracefully terminate the job, cleaning up resources, etc., if it is cancelled. If the job can block, e.g., on IO, then you will need to ensure the block is interrupt-able and notify it asynchronously, or allow the block to periodically time-out and resume it's block after checking for cancellation.

See the following articles on how this done in Java:

How to stop a java thread gracefully? How to properly stop the Thread in Java? http://docs.oracle.com/javase/7/docs/api/java/nio/channels/AsynchronousChannel.html

Community
  • 1
  • 1
Jan Nielsen
  • 10,892
  • 14
  • 65
  • 119
  • what is the commonly followed practice to handle this scenario in S/W development? Any environment, say C# with winforms or WPF. I dont like both solutions, is there any better ways? – Coder777 Feb 23 '14 at 05:47