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

c#, multithreading

Solution

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.

Problem

How do I abort, pause and resume threads in C#? Related question: Is there a way to indefinitely pause a thread?

Original source

Related problems