9

How do I abort, pause and resume threads in C#?

Related question:

Is there a way to indefinitely pause a thread?

Community
  • 1
  • 1

4 Answers4

23

In general, don't pause (or abort) a Thread - you can't normally tell what it was doing, and this could lead to all sorts of locking issues, such as an a lock that isn't released, or a type initializer (static constructor) that is left hanging.

You might, however, pause code through more elegant methods - for example, using a ManualResetEvent in your loop that external code (on another thread) can open and close:

// worker loop
while(alive) {
    // if the gate is closed, wait up to 5 seconds; if still not
    // open, go back to the loop-start to re-check "alive"
    if (!gate.WaitOne(5000)) continue;

    // do work...
}

Then another thread with access (probably indirect) can pause (Reset) and resume (Set) the worker, but in the knowledge that it only pauses in a safe state.


Re your comment (on another reply) - it sounds like you have a reader and writer; ideal for a producer/consumer scenario. I have a an example on this question of how to write a producer/consumer with a capped size (so it won't swamp if the consumer runs slow) - the consumer blocks if there is no data, and the producer blocks if there is too much.

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Hey, this is the second +1 I've had to give you today for stating one of my mantras: threads should be responsible for their own lifetimes, otherwise you get into all sorts of problems like deadlocks and lost data. After this one, no more soup for you today :-) – paxdiablo Jun 28 '09 at 10:12
  • That's fine, I'm capped now ;-p – Marc Gravell Jun 28 '09 at 10:30
  • Im trying to get a collection of tasks to pause, allowing me to update a data table, before recommencing them all (They all read from the same datatable). Do you know of anyway i can know when the last task in the collection has reached the end of the datatable. Is ManualResetEvent the correct approach for my problem? Thanks for your time. – Hans Rudel Nov 12 '12 at 11:22
  • I did use `ManualResetEvent` to control the state of thread,but when I test this mechanism in VirtualBox hosted windows XP,it failed. – zionpi Mar 25 '15 at 02:00
8

If you've aborted the thread, it won't be able to run again. You could run the same task (e.g. the same ThreadStart delegate) on a different thread, but that's not running the same thread again.

I would strongly advise you not to hard-abort threads unless your app is coming down. Instead, work out a graceful thread termination protocol instead, so you can tell a task that you want it to stop. The same goes for "pausing" a thread - you really don't want to suspend a thread while it's holding some critical resource.

Perhaps if you could tell us more about your situation, we could help more. Graceful pause/resume or cancel functionality is reasonably easy to achieve with monitors (see the second half of the page) or wait handles.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 4
    I hereby propose a ban on both Jon Skeet and Marc Gravell... you are forbidden from answering complicated questions for the first 30 minutes and simple questions forever :P – Marcel Popescu Jun 28 '09 at 09:00
  • my applicaion reading from rfid reader by contnuiasly thread and write tag's id data into database, at writing data on that tage i want to abort or pause that thread and resume it and how to pause specific thread plz help me in that aspect –  Jun 28 '09 at 09:08
1

If you need to pause a thread for a while, get it to call Sleep.

If you need it to pause until some condition becomes true, use a condition variable or a wait.

For condition variables in .NET use Monitor methods including Wait and Pulse; see here for an introduction. (Windows Vista also added native Condition Variable support to the Win32 API, but that is a completely separate implementation, .NET has had conditional variable support since V1.0).

For Waits: that is ant use of WaitAny or WaitAny method overloads of the WaitHandle class to wait on one of the various Win32 synchronisation object types exposed in .NET as subclasses of WaitHandle (events, mutexes, waitable timers and so forth).

Richard
  • 106,783
  • 21
  • 203
  • 265
Rhythmic Fistman
  • 34,352
  • 5
  • 87
  • 159
0

If you want to do it even though it's a bad idea, look at the Suspend and Resume methods - MSDN has more info on the subject, including why it's a bad idea.

To repeat - I strongly advise you to go with Marc Gravell's solution instead.

Marcel Popescu
  • 3,146
  • 3
  • 35
  • 42
  • Dear newbie, here is a gun and while I'm at it you can have some dumdum bullets, be really careful never to use this stuff its really dangerous :P – Sam Saffron Jun 28 '09 at 09:29
  • Hey, I'm a big fan of Heinlein's "an armed society is a polite society" mantra, so yea, if after all these warnings he wants to go with Suspend/Resume... at least I answered his question :) – Marcel Popescu Jun 28 '09 at 09:31