Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wake up a thread when event occurs

I would like to achieve a following communication between two threads:

Thread Alpha does something, and then suspends itself. Next the second thread(Beta) raises and event which resumes the Alpha thread. The cycle goes on...

I did something like below but I am not sure if it is a proper design. Also I've notice that Thread.Suspend() and Thread.Resume() are deprecated. I'm looking forward to hearing any advice about this implementation and what is preferred to replace deprecated methods.

namespace ThreadTester
{
    delegate void ActionHandler();

    class Alpha
    {
        internal Thread alphaThread;
        internal void Start()
        {
            while (true)
            {
                this.alphaThread.Suspend();
                Console.WriteLine("Alpha");
            }
        }
        internal void Resume()
        {
            while (this.alphaThread.ThreadState == ThreadState.Suspended)
            this.alphaThread.Resume();
        }
    }

    class Beta
    {
        internal event ActionHandler OnEvent;
        internal void Start()
        {
            for (int i = 0; i < 15; i++)
            {
                OnEvent();
                Thread.Sleep(1000);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Alpha alpha = new Alpha();
            alpha.alphaThread = new Thread(new ThreadStart(alpha.Start));
            alpha.alphaThread.Start();
            while (!alpha.alphaThread.IsAlive) ;

            Beta beta = new Beta();
            beta.OnEvent += new ActionHandler(alpha.Resume);
            Thread betaThread = new Thread(new ThreadStart(beta.Start));
            betaThread.Start();
        }
    }
}
like image 999
nan Avatar asked Nov 15 '10 19:11

nan


1 Answers

This is where you typically use wait handles, in particular event wait handles.

If you call the WaitOne method on a wait handle, it will block your thread until some other thread calls Set on the same wait handle.

There are two important simple flavors of event wait handles: AutoResetEvent will automatically reset itself after a thread passes through WaitOne. ManualResetEvent will only reset itself if you call Reset.

like image 97
Joren Avatar answered Sep 28 '22 07:09

Joren