Tuesday, September 22, 2015

IPC via Standard In and Out in C#.Net

When to communicate via console instead of service based IPC

IPC is an essential feature of large software systems. We cannot build large systems with just process. Technically we can but it will not scale to the larger audience. Another problem is stability. There are many ways to achieve inter process communication which is listed in wiki. Normally people prefer service based communication as it will scale easily to more machines.

If we are sure that 2 processes are 
  • Always going to run on same machine.
  • They may not be available always. Sometimes the destination process might be spawn by source. Sometimes source may need go down after initiating the destination after getting the 'take over'signal.
we can use simple mechanisms to establish the communication.

Command line arguments

If the communication is
  • From source to destination only
  • One time 
  • Destination is spawn by source process 
  • With small data
We can use command line argument passing mechanism from the source to destination.

Using Process.StandardInput.WriteLine

If the communication payload is big passing via the command line arguments is not the good option. We can use standard input and output streams instead. Below is the C# code snippets for source as well as destination. Even it can be 2 instances of same executable.
Source code for destination exe There are multiple ways to write to the standard in stream such as using the StreamWriter and all. If we use writer in source and ReadLine in destination there are chances that programs may wait on ReadLine statements unless we explicitly flush. So better use simple console write and read line methods.

Using unique/temp files and pass the file name via commandline args

If the communication payload is enormous or its binary and mainly one way from source to destination, we can use temp files to pass data. Things to remember

  • Better generate a guid and use that as file name. 
  • Close the file after writing at the source.
  • Keep it in a temp location.
  • Let the destination file delete the temp file once its read
  • Still have cleanup routine to delete the temp files if anything remains
  • Do not use this mechanism for 2 way communication with FileSystemWatcher or passing the file name via Standard in/out streams.

Why to subscribe to OutputDataReceived event

There are now 2 parties involved in communication and there are chances that 2 of those may wait for the input from others. So better use OutputDataReceived event to avoid such deadlocks.



1 comment:

Blogger said...

Did you know that you can make money by locking special pages of your blog or site?
Simply open an account with AdscendMedia and embed their content locking tool.