I have a program that stores objects into a priority queue, and Dequeue's them at certain times of a day to send over a TCP connection.
Right now, I'm doing this by calling thread.sleep for however many seconds until the next runtime of whatever's coming out next of the priority queue.
while (MyQueue.NumItems > 0)
{
int secondsnow = (int)DateTime.Now.TimeOfDay.TotalSeconds;
int nextTime = MyQueue.Peek().gettime();
// Gets the time in seconds when the next object on the queue is to be sent
Thread.Sleep(TimeSpan.FromSeconds(nextTime - secondsnow));
// Sleeps until that time
tcpclient.SendMessage(stream, MyQueue.Dequeue());
// Send that data over my connection
}
My next goal is to incorporate a TCP Listener into the program that will sit there waiting for a client to send it data in the form of an object for me to dynamically put into my priority queue while the program is running. The TCP listener itself is a blocking call and needs to unblock whenever the above code needs to dequeue an object at the stated time.
This is a rough idea of the TCP Listener code:
while(true)
{
// Perform a blocking call to accept requests.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Process data and add to the priority queue
MyQueue.enqueue(new myObject(bytes));
}
// Shutdown and end connection
client.Close();
}
}
What's the best way for me to execute both loops at the same time, with one of them being a blocking call and the other being time dependent, while preventing any deadlock situations with both loops accessing the priority queue? I'm new to multithreading so I'm stll pretty confused by the process in which threads start and block.