How to unlock ConnectNamedPipe and ReadFile? [FROM#]

I have a class (NamedPipeManager) that has a thread (PipeThread) that waits for NamedPipe to connect using (ConnectNamedPipe) and then reads (ReadFile) - these are blocking calls (not overlapping) - however, there comes a time when I want to unlock them - for example, when the calling class tries to stop NamedPipeManager ...

How can I reinstall it? Using Thread.abort? Thread.interrupt? Is there a proper way to handle this? Refer to the code below that illustrates my current situation.

main() { NamedPipeManager np = new NamedPipeManager(); ... do stuff ... ... do stuff ... np.Stop(); // at this point I want to stop waiting on a connection } class NamedPipeManager { private Thread PipeThread; public NamedPipeManager { PipeThread = new Thread(new ThreadStart(ManagePipes)); PipeThread.IsBackground = true; PipeThread.Name = "NamedPipe Manager"; PipeThread.Start(); } private void ManagePipes() { handle = CreateNamedPipe(..., PIPE_WAIT, ...); ConnectNamedPipe(handle, null); // this is the BLOCKING call waiting for client connection ReadFile(....); // this is the BLOCKING call to readfile after a connection has been established } public void Stop() { /// This is where I need to do my magic /// But somehow I need to stop PipeThread PipeThread.abort(); //?? my gut tells me this is bad } }; 

So, in the Stop () function - how would I gracefully unlock a call to ConnectNamedPipe (...) or ReadFile (...)?

Any help would be greatly appreciated. Thanks,

+6
c ++ c # pipe named-pipes pinvoke
source share
2 answers

Starting with Windows Vista, there is a CancelSynchronousIO function available for streams. I don't think there is a C # shell for it, so you will need to use PInvoke to call it.

Prior to Vista, there is no way to perform such an operation gracefully. I would advise against using thread cancellation (which may work, but does not qualify as elegant). Your best approach is to use overlapping IO.

+4
source share

It seems to work on VC6.0, WinXP, if I try to abort ConnectNamedPipe on DeleteFile("\\\\.\\pipe\\yourpipehere");

So just specify a name, not a descriptor.

+3
source share

All Articles