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();
}
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With