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();
}
}
}
Typically threads are used to allow > 1 item of work to be processed in parallel. I’m curious about why your design requires thread A to sleep while thread B does something, then wake up and carry on working. Why not just have Thread A do that work itself?
You might benefit from using .Net 4’s Task Parallel Library – Thread A could then initiate an asynchronous Task which is automagically executed on a separate thread, and the result made available to Thread A without the need for explicit inter-thread signalling (which can result in a hung app if either Thread A or B malfunctions).