如何解锁ConnectNamedPipe和ReadFile?[C#]

Sha*_*n00 7 c# c++ pinvoke pipe named-pipes

我有一个类(NamedPipeManager),它有一个线程(PipeThread)等待使用(ConnectNamedPipe)的NamedPipe连接,然后读取(ReadFile) - 这些是阻塞调用(不重叠) - 但是有一点我想要解锁它们 - 例如当调用类试图停止NamedPipeManager时...

我怎么能打断它呢?使用Thread.abort?了Thread.interrupt?有没有正确的方法来处理这个?请参阅下面的代码,该代码说明了我目前的情况

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
}
};
Run Code Online (Sandbox Code Playgroud)

那么,在函数Stop()中 - 我如何优雅地解锁对ConnectNamedPipe(...)或ReadFile(...)的调用?

任何帮助,将不胜感激.谢谢,

Ser*_*nil 6

这似乎是工作VC6.0,WinXP的,如果我尝试中断ConnectNamedPipeDeleteFile("\\\\.\\pipe\\yourpipehere");

所以只需指定名称,而不是句柄.


Mar*_*wis 5

从Windows Vista开始,可以为线程提供CancelSynchronousIO操作.我不认为它有一个C#包装器,所以你需要使用PInvoke来调用它.

在Vista之前,没有办法优雅地执行这样的操作.我建议不要使用线程取消(这可能有效,但不符合优雅).您最好的方法是使用重叠IO.