title: Breaking ReadFile() blocking - Named Pipe (Windows API)
body: <p>To simplify, this is a situation where a NamedPipe SERVER is waiting for a NamedPipe CLIENT to write to the pipe (using WriteFile())</p>
  
  <p>The Windows API that is blocking is ReadFile()</p>
  
  <p>The Server has created the synchronous pipe (no overlapped I/O) with blocking enabled</p>
  
  <p>The client has connected, and now the server is waiting for some data.</p>
  
  <p>In the normal flow of things, the client sends some data and the server processes it and then returns to ReadFile() to wait for the next chunk of data.</p>
  
  <p>Meanwhile an event occurs (user input for example) and the NamedPipe SERVER must now execute some other code, which it cannot do while the ReadFile() is blocking.</p>
  
  <p>At this point I need to mention that the NamedPipe Client is not my application, so I have no control over it. I cannot make it send a few bytes to unblock the server. It is just going to sit there and send no data. Since I do not have control of the Client implementation I cannot change anything on that end.</p>
  
  <p>One solution would be to create a separate thread in which all ReadFile() operations are performed. That way when the event occurs, I can just process the code. The problem with that, is that the event also requires a separate thread, so now I have two additional threads for each instance of this server. Since this needs to be scalable, this is undesirable.</p>
  
  <p>From another thread I have tried calling</p>
  
  <pre><code> DisconnectNamedPipe()
  </code></pre>
  
  <p>and</p>
  
  <pre><code> CloseHandle()
  </code></pre>
  
  <p>they both will not return (until the client writes to the pipe.)</p>
  
  <p>I cannot connect to the same pipe and write a few bytes because:</p>
  
  <p>"All instances of a named pipe share the same pipe name, but each instance has 
  its own buffers and handles, and provides a separate conduit for client/server 
  communication."</p>
  
  <p><a href="http://msdn.microsoft.com/en-us/library/aa365590.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa365590.aspx</a></p>
  
  <p>I need a way to fake it out, So the $64k dollar question is:</p>
  
  <p>How can I break the blocking of ReadFile()?</p>