How to pause a thread at once in C#?

116 Views Asked by At

I use ManualResetEnvent to pause/continue a thread. The code example is below.

private _rstEvent = new ManualResetEvent(true);

public void DoSomeWork()
{
    while(judgementValue)
    {
        _rstEvent.WaitOne();
        ...
    }
}

public void Pause()
{
    _rstEvent.Reset();
}

public void Continue()
{
    _rstEvent.Set();
}

The problem is what if the while loop is large, which means every loop in the while statement has many operations to do. The thread will keep going until meet the next _rstEvent.WaitOne();. Is there a way to pause the thread at once except the deprecated suspend?

1

There are 1 best solutions below

1
On BEST ANSWER

The problem with Suspend, Abort and the like is that you're trying to do something to another thread which could literally be doing anything at the time.

It has been repeatedly observed that this can lead to difficult to diagnose bugs where e.g. none of your current threads can obtain a lock because the thread that held the lock has been suspended or aborted and thus will never release the lock (substitute in any other resource also).

This is why modern threading mechanisms are built around cooperative primitives where the thread itself checks (at appropriate moments) whether it's being asked to suspend or abort and can ensure that it only does so when not holding any resources.

There's no reason your loop code cannot check the event multiple times per iteration, whenever it is appropriate.