Tuesday, September 1, 2009

Studying Interprocess Communication

Today I had to solve a simple problem. Let's say there are two processes running on one computer. The first service polls a database for print jobs. As soon as a job is found, a second service has to send the job to the printer. So, effectively, I have to pass some data from one local service to another.

The first, "amateurish" solution that came to my mind was to write data to a text file by the "polling" service and read from that file by "printing" service. But I thought that the task like this should be a standard one and looked around. Here's one of the examples I found:

.NET 3.5 Adds Named Pipes Support

Here's the probably the simplest working example: First, I need to create two windows services. I add a timer to each service. I also add an event log to each of the services to be able to check if they work. One of the services will be a "server". Here's what goes into it's timer_Elapsed:

using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testPipe", PipeDirection.Out))
{
pipeServer.WaitForConnection();

try
{
using (StreamWriter sw = new StreamWriter(pipeServer))
{
sw.AutoFlush = true;
string dt = DateTime.Now.ToString();
sw.WriteLine(dt);
pollingEventLog.WriteEntry(dt + " written by the server");
}
}
catch (IOException ex)
{
pollingEventLog.WriteEntry(ex.Message);
}
}

The other service will be a "client". Here's what goes into it's timer_Elapsed:

using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testPipe", PipeDirection.In))
{
pipeClient.Connect();
using (StreamReader sr = new StreamReader(pipeClient))
{
string temp;
while ((temp = sr.ReadLine()) != null)
{
printManagerEventLog.WriteEntry(temp + " read by the client");
}
}
}

This is it - after both services are compiled, installed and started, their cooperation can be observed through the Event Log. Total time including googling, understanding the concept and implementing the working example - under 30 minutes.

by . Also posted on my website

No comments: