Question about terminating a thread cleanly in .NET
Asked Answered
G

8

70

I understand Thread.Abort() is evil from the multitude of articles I've read on the topic, so I'm currently in the process of ripping out all of my abort's in order to replace it for a cleaner way; and after comparing user strategies from people here on stackoverflow and then after reading "How to: Create and Terminate Threads (C# Programming Guide)" from MSDN both which state an approach very much the same -- which is to use a volatile bool approach checking strategy, which is nice, but I still have a few questions....

Immediately what stands out to me here, is what if you do not have a simple worker process which is just running a loop of crunching code? For instance for me, my process is a background file uploader process, I do in fact loop through each file, so that's something, and sure I could add my while (!_shouldStop) at the top which covers me every loop iteration, but I have many more business processes which occur before it hits it's next loop iteration, I want this cancel procedure to be snappy; don't tell me I need to sprinkle these while loops every 4-5 lines down throughout my entire worker function?!

I really hope there is a better way, could somebody please advise me on if this is in fact, the correct [and only?] approach to do this, or strategies they have used in the past to achieve what I am after.

Thanks gang.

Further reading: All these SO responses assume the worker thread will loop. That doesn't sit comfortably with me. What if it is a linear, but timely background operation?

Godinez answered 3/9, 2010 at 0:0 Comment(3)
Think of it this way: do you really want your long-running process to abort at any arbitrary time when it might have been in the middle of some state-mutating processing? The reason you need to add checks in the midst of the code (not necessarily in a loop, though that's common) is because only you, as the developer, know enough about your code to know when it's safe to stop. If the thread is blocking waiting on synchronization signals, see the Interrupt() method mentioned in the answers.Tetrarch
I'm not denying it shouldn't be handled by the user (me), it just looked like a lot of superfluous code. It would be nice somehow to set up something like how a try, catch runs, constantly monitoring, as soon as a flag is false, then maybe return; from the function. I don't know.Godinez
It turns out here what I might have wanted was Thread.Interrupt. Although I think I prefer a bool flag check at least for now to absolutely ensure the integrity of my app state.Godinez
R
115

Unfortunately there may not be a better option. It really depends on your specific scenario. The idea is to stop the thread gracefully at safe points. That is the crux of the reason why Thread.Abort is not good; because it is not guaranteed to occur at safe points. By sprinkling the code with a stopping mechanism you are effectively manually defining the safe points. This is called cooperative cancellation. There are basically 4 broad mechanisms for doing this. You can choose the one that best fits your situation.

Poll a stopping flag

You have already mentioned this method. This a pretty common one. Make periodic checks of the flag at safe points in your algorithm and bail out when it gets signalled. The standard approach is to mark the variable volatile. If that is not possible or inconvenient then you can use a lock. Remember, you cannot mark a local variable as volatile so if a lambda expression captures it through a closure, for example, then you would have to resort to a different method for creating the memory barrier that is required. There is not a whole lot else that needs to be said for this method.

Use the new cancellation mechanisms in the TPL

This is similar to polling a stopping flag except that it uses the new cancellation data structures in the TPL. It is still based on cooperative cancellation patterns. You need to get a CancellationToken and the periodically check IsCancellationRequested. To request cancellation you would call Cancel on the CancellationTokenSource that originally provided the token. There is a lot you can do with the new cancellation mechanisms. You can read more about here.

Use wait handles

This method can be useful if your worker thread requires waiting on an specific interval or for a signal during its normal operation. You can Set a ManualResetEvent, for example, to let the thread know it is time to stop. You can test the event using the WaitOne function which returns a bool indicating whether the event was signalled. The WaitOne takes a parameter that specifies how much time to wait for the call to return if the event was not signaled in that amount of time. You can use this technique in place of Thread.Sleep and get the stopping indication at the same time. It is also useful if there are other WaitHandle instances that the thread may have to wait on. You can call WaitHandle.WaitAny to wait on any event (including the stop event) all in one call. Using an event can be better than calling Thread.Interrupt since you have more control over of the flow of the program (Thread.Interrupt throws an exception so you would have to strategically place the try-catch blocks to perform any necessary cleanup).

Specialized scenarios

There are several one-off scenarios that have very specialized stopping mechanisms. It is definitely outside the scope of this answer to enumerate them all (never mind that it would be nearly impossible). A good example of what I mean here is the Socket class. If the thread is blocked on a call to Send or Receive then calling Close will interrupt the socket on whatever blocking call it was in effectively unblocking it. I am sure there are several other areas in the BCL where similiar techniques can be used to unblock a thread.

Interrupt the thread via Thread.Interrupt

The advantage here is that it is simple and you do not have to focus on sprinkling your code with anything really. The disadvantage is that you have little control over where the safe points are in your algorithm. The reason is because Thread.Interrupt works by injecting an exception inside one of the canned BCL blocking calls. These include Thread.Sleep, WaitHandle.WaitOne, Thread.Join, etc. So you have to be wise about where you place them. However, most the time the algorithm dictates where they go and that is usually fine anyway especially if your algorithm spends most of its time in one of these blocking calls. If you algorithm does not use one of the blocking calls in the BCL then this method will not work for you. The theory here is that the ThreadInterruptException is only generated from .NET waiting call so it is likely at a safe point. At the very least you know that the thread cannot be in unmanaged code or bail out of a critical section leaving a dangling lock in an acquired state. Despite this being less invasive than Thread.Abort I still discourage its use because it is not obvious which calls respond to it and many developers will be unfamiliar with its nuances.

Rillings answered 3/9, 2010 at 2:10 Comment(5)
Very informative and gives some great examples. Thank you very much.Godinez
Points awarded for diversity of answer. Thanks.Godinez
If a thread will call an unmanaged method which may take an annoyingly long time and should be killable (recognizing that killing the DLL may leave it in a bad state, but shouldn't affect anything outside itself), what would be the effect of having the thread acquire a lock and hold it at all times except when it would be safe to kill? Would it be safe for an outside thread which acquired that lock to use Thread.Abort since the thread to be aborted couldn't be in any sort of bad spot (or else it would hold the lock)?Coverup
@supercat: Good question. The problem is that most of the time the ThreadAbortException will not be injected into the thread while it is in unmanaged code anyway. I'm not sure I quite understand the point of said lock, but I believe I can infer your thought process...is it because the lock would delay abort injection? Also, Hans Passant has some excellent advice for this situation. Basically, the only safe way is to run the unmanaged code out-of-process.Rillings
One extremely important thing about Thread.Interrupt() that isn't mentioned here - ThreadInterruptedException will be thrown from any lock statement or call to Monitor.Enter() that has contention on it because it is considered to be a wait state in .NET. This means unless you handle the error on every lock and Monitor.Enter() statement in your app and any code that is in play that you don't own, it is totally unpredictable what could throw the exception when you call Thread.Interrupt() or what state it is in when the exception is thrown.Marmalade
M
13

Well, unfortunately in multithreading you often have to compromise "snappiness" for cleanliness... you can exit a thread immediately if you Interrupt it, but it won't be very clean. So no, you don't have to sprinkle the _shouldStop checks every 4-5 lines, but if you do interrupt your thread then you should handle the exception and exit out of the loop in a clean manner.

Update

Even if it's not a looping thread (i.e. perhaps it's a thread that performs some long-running asynchronous operation or some type of block for input operation), you can Interrupt it, but you should still catch the ThreadInterruptedException and exit the thread cleanly. I think that the examples you've been reading are very appropriate.

Update 2.0

Yes I have an example... I'll just show you an example based on the link you referenced:

public class InterruptExample
{
    private Thread t;
    private volatile boolean alive;

    public InterruptExample()
    {
        alive = false;

        t = new Thread(()=>
        {
            try
            {
                while (alive)
                {
                    /* Do work. */
                }
            }
            catch (ThreadInterruptedException exception)
            {
                /* Clean up. */
            }
        });
        t.IsBackground = true;
    }

    public void Start()
    {
        alive = true;
        t.Start();
    }


    public void Kill(int timeout = 0)
    {
        // somebody tells you to stop the thread
        t.Interrupt();

        // Optionally you can block the caller
        // by making them wait until the thread exits.
        // If they leave the default timeout, 
        // then they will not wait at all
        t.Join(timeout);
    }
}
Monodic answered 3/9, 2010 at 0:6 Comment(3)
Do you have an example of how Interrupt is used? Thanks Lirik.Godinez
@GONeale, I've posted an example for you now... let me know if it's helpful.Monodic
Ah now that makes sense. I had a hunch it raised an exception at any possible point, and the idea was we had to catch it. Ok I will make a decision between the suggested solutions, thanks.Godinez
U
9

If cancellation is a requirement of the thing you're building, then it should be treated with as much respect as the rest of your code--it may be something you have to design for.

Lets assume that your thread is doing one of two things at all times.

  1. Something CPU bound
  2. Waiting for the kernel

If you're CPU bound in the thread in question, you probably have a good spot to insert the bail-out check. If you're calling into someone else's code to do some long-running CPU-bound task, then you might need to fix the external code, move it out of process (aborting threads is evil, but aborting processes is well-defined and safe), etc.

If you're waiting for the kernel, then there's probably a handle (or fd, or mach port, ...) involved in the wait. Usually if you destroy the relevant handle, the kernel will return with some failure code immediately. If you're in .net/java/etc. you'll likely end up with an exception. In C, whatever code you already have in place to handle system call failures will propagate the error up to a meaningful part of your app. Either way, you break out of the low-level place fairly cleanly and in a very timely manner without needing new code sprinkled everywhere.

A tactic I often use with this kind of code is to keep track of a list of handles that need to be closed and then have my abort function set a "cancelled" flag and then close them. When the function fails it can check the flag and report failure due to cancellation rather than due to whatever the specific exception/errno was.

You seem to be implying that an acceptable granularity for cancellation is at the level of a service call. This is probably not good thinking--you are much better off cancelling the background work synchronously and joining the old background thread from the foreground thread. It's way cleaner becasue:

  1. It avoids a class of race conditions when old bgwork threads come back to life after unexpected delays.

  2. It avoids potential hidden thread/memory leaks caused by hanging background processes by making it possible for the effects of a hanging background thread to hide.

There are two reasons to be scared of this approach:

  1. You don't think you can abort your own code in a timely fashion. If cancellation is a requirement of your app, the decision you really need to make is a resource/business decision: do a hack, or fix your problem cleanly.

  2. You don't trust some code you're calling because it's out of your control. If you really don't trust it, consider moving it out-of-process. You get much better isolation from many kinds of risks, including this one, that way.

Upwind answered 3/9, 2010 at 0:37 Comment(1)
Good for pointing out that cancellation should be a design decision (when possible - it not always is if you didn't write underlying code), not an afterthought.Antiquate
B
3

The best answer largely depends on what you're doing in the thread.

  • Like you said, most answers revolve around polling a shared boolean every couple lines. Even though you may not like it, this is often the simplest scheme. If you want to make your life easier, you can write a method like ThrowIfCancelled(), which throws some kind of exception if you're done. The purists will say this is (gasp) using exceptions for control flow, but then again cacelling is exceptional imo.

  • If you're doing IO operations (like network stuff), you may want to consider doing everything using async operations.

  • If you're doing a sequence of steps, you could use the IEnumerable trick to make a state machine. Example:

<

abstract class StateMachine : IDisposable
{
    public abstract IEnumerable<object> Main();

    public virtual void Dispose()
    {
        /// ... override with free-ing code ...
   }

   bool wasCancelled;

   public bool Cancel()
   {
     // ... set wasCancelled using locking scheme of choice ...
    }

   public Thread Run()
   {
       var thread = new Thread(() =>
           {
              try
              {
                if(wasCancelled) return;
                foreach(var x in Main())
                {
                    if(wasCancelled) return;
                }
              }
              finally { Dispose(); }
           });
       thread.Start()
   }
}

class MyStateMachine : StateMachine
{
   public override IEnumerabl<object> Main()
   {
       DoSomething();
       yield return null;
       DoSomethingElse();
       yield return null;
   }
}

// then call new MyStateMachine().Run() to run.

>

Overengineering? It depends how many state machines you use. If you just have 1, yes. If you have 100, then maybe not. Too tricky? Well, it depends. Another bonus of this approach is that it lets you (with minor modifications) move your operation into a Timer.tick callback and void threading altogether if it makes sense.

and do everything that blucz says too.

Baccarat answered 3/9, 2010 at 0:40 Comment(2)
Thanks dude. Appreciate the response.Godinez
The notion of "exceptions shouldn't be used for flow control" basically means that if the code that throws an exception knows where it will be caught, it should use some other means to "get there". Cancellation will often require outputting many layers of nested loops, and inner-loop code will often know nothing about the outer loops or how to break out of them.Coverup
F
2

Perhaps the a piece of the problem is that you have such a long method / while loop. Whether or not you are having threading issues, you should break it down into smaller processing steps. Let's suppose those steps are Alpha(), Bravo(), Charlie() and Delta().

You could then do something like this:

    public void MyBigBackgroundTask()
    {
        Action[] tasks = new Action[] { Alpha, Bravo, Charlie, Delta };
        int workStepSize = 0;
        while (!_shouldStop)
        {
            tasks[workStepSize++]();
            workStepSize %= tasks.Length;
        };
    }

So yes it loops endlessly, but checks if it is time to stop between each business step.

Fallow answered 3/9, 2010 at 0:12 Comment(1)
Ok thanks. But it does boil down to the same approach. No problem.Godinez
C
2

You don't have to sprinkle while loops everywhere. The outer while loop just checks if it's been told to stop and if so doesn't make another iteration...

If you have a straight "go do something and close out" thread (no loops in it) then you just check the _shouldStop boolean either before or after each major spot inside the thread. That way you know whether it should continue on or bail out.

for example:

public void DoWork() {

  RunSomeBigMethod();
  if (_shouldStop){ return; }
  RunSomeOtherBigMethod();
  if (_shouldStop){ return; }
  //....
}

Carcinoma answered 3/9, 2010 at 0:36 Comment(0)
R
2

Instead of adding a while loop where a loop doesn't otherwise belong, add something like if (_shouldStop) CleanupAndExit(); wherever it makes sense to do so. There's no need to check after every single operation or sprinkle the code all over with them. Instead, think of each check as a chance to exit the thread at that point and add them strategically with this in mind.

Recovery answered 3/9, 2010 at 0:53 Comment(0)
E
1

All these SO responses assume the worker thread will loop. That doesn't sit comfortably with me

There are not a lot of ways to make code take a long time. Looping is a pretty essential programming construct. Making code take a long time without looping takes a huge amount of statements. Hundreds of thousands.

Or calling some other code that is doing the looping for you. Yes, hard to make that code stop on demand. That just doesn't work.

Emblaze answered 3/9, 2010 at 0:19 Comment(2)
Ok well I don't have that many :) Yeah for the most part it probably will be contained at the top in my for loop iterating through each file, my general worry was in some data packet sending as well, but I can re-loop inside there for the writing of bytes I suppose.Godinez
By the way on this Hans, after successfully implementing my check with a bool I realised why I originally had a problem with a loop check and the reason I had long running code, it wasn't because of many lines, it was simply because some lines called functions off to remote WCF calls which had to wait upon a response, which took time.Godinez

© 2022 - 2024 — McMap. All rights reserved.