-1
islem = new Thread(new ThreadStart(ilk));
         islem2 = new Thread(new ThreadStart(ikinci));
         islem3 = new Thread(new ThreadStart(ucuncu));
         islem4 = new Thread(new ThreadStart(dorduncu));
         islem.Start();
         islem2.Start();
         islem3.Start();
         islem4.Start();



        if (!islem.IsAlive)
        {
            islem2.Suspend();
            islem3.Suspend();
            islem4.Suspend();
        }

I want to do when islem is done. Other threads suspend but it doesn't work I read about ManualResetEvent but I can't figure out multi-threading examples.They works just one thread simples. Also I read http://www.albahari.com/threading/part4.aspx#_Suspending_and_Resuming this paper to and look similar questions like C# controlling threads (resume/suspend) How to pause/suspend a thread then continue it? Pause/Resume thread whith AutoResetEvent I am working multi - thread objects

GKS
  • 3
  • 3

1 Answers1

1

If you just need to cancel the worker threads, the very simplest approach is to use a flag. You have to mark the flag volatile to ensure all threads are using the same copy.

private volatile bool _done = false;

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        if (_done) return; //Someone else solved the problem, so exit.
        ContinueSolvingTheProblem();
    }
    _done = true; //Tell everyone else to stop working.
}

If you truly want to pause (I'm not sure why) you can use a ManualResetEvent. This allows blocking behavior without consuming resources for the paused thread.

//When signalled, indicates threads can proceed.
//When reset, threads should pause as soon as possible.
//Constructor argument = true so it is set by default
private ManualResetEvent _go = new ManualResetEvent(true);

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        _go.WaitOne();  //Pause if the go event has been reset
        ContinueSolvingTheProblem();
    }
    _go.Reset();  //Reset the go event in order to pause the other threads
}

You can also combine the approaches, e.g. if you wanted to be able to pause the threads, do some more work, then cancel them:

private volatile bool _done = false;
private ManualResetEvent _go = new ManualResetEvent(true);

void Main()
{
    StartWorkerThreads();
}

void WorkerThread()
{
    while (true)
    {
        if (_done) return; //Exit if problem has been solved
        _go.WaitOne();  //Pause if the go event has been reset
        if (_done) return; //Exit if problem was solved while we were waiting
        ContinueSolvingTheProblem();
    }
    _go.Reset();  //Reset the go event in order to pause the other threads
    if (VerifyAnswer())
    {
        _done = true; //Set the done flag to indicate all threads should exit
    }
    else
    {
        _go.Set(); //Tell other threads to continue
    }
}
John Wu
  • 50,556
  • 8
  • 44
  • 80