Many times we come across situations were need to continuously execute a block of code
For instance reading data from network port (socket program), or from RFID where we create secondary thread for continuously reading and another thread for same data manipulation
Let me demonstrate with a basic read from keyboard (on primary thread) and write (on secondary thread) in console application with queue
using
System.Threading;
namespace
ConsoleApplication2
{
class Program
{
static Queue<string>
q = new Queue<string>();
static Thread ThreadObj;
static void ReadMethod()
{
while
(true)
{
if
(q.Count > 0)
{
}
}
}
static void Main(string[]
args)
{
ThreadObj = new Thread(new ThreadStart(ReadMethod));
ThreadObj.Start();
loc:
}
}
}
Where read method executes while loop infinite times, with a check is made if queue has string item if yes write it and continue with next iteration
obviously we need to avoid while loop to continue execution until there is an enqueue happen on queue, to do that consider the below example
class Program
{
static Queue<string>
q = new Queue<string>();
static Thread ThreadObj;
static object LockObj = new object();
static void ReadMethod()
{
while
(true)
{
if
(q.Count == 0)
lock
(LockObj)
{
//hold a lock on LockObj and wait for a signal if queue is empty
Monitor.Wait(LockObj);
}
string
str = q.Dequeue();
Console.WriteLine(string.Format("Dequeued
item {0}", str));
}
}
static void Main(string[]
args)
{
ThreadObj = new Thread(new ThreadStart(ReadMethod));
ThreadObj.Start();
loc:
string
input = Console.ReadLine();
q.Enqueue(input);
lock
(LockObj)
{
//signal
to continue on LockObj
Monitor.Pulse(LockObj);
}
goto
loc;
}
}
From the above code ReadMethod while loop is blocked and put on wait until queue is Enqueued, ReadMethod uses Monitor.Wait(LockObj) which blocks the current thread execution on static object LockObj until receives a signal using Monitor.Pulse(LockObj).
Note : Object synchronization Monitor.Pulse and Monitor.Wait must be called from an synchronized block of code hence we use lock keyword(similarly you can user Monitor.Enter, Monitor.Exit methods or Synchronization attribute to synchronize between threads).
Let us put the above code in ready made form by extending .Net library class Queue
Take 1

Join the conversation! Your thoughts help the community grow.