7

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

我该如何打断它?使用 Thread.abort?线程中断?有没有合适的方法来处理这个?请参阅下面的代码,它说明了我目前的情况

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
}
};

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

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

4

2 回答 2

7

ConnectNamedPipe如果我尝试中断, 它似乎正在 VC6.0,WinXPDeleteFile("\\\\.\\pipe\\yourpipehere");

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

于 2011-10-21T08:58:51.607 回答
5

从 Windows Vista 开始,有一个可用于线程的CancelSynchronousIO操作。我认为它没有 C# 包装器,因此您需要使用 PInvoke 来调用它。

在 Vista 之前,实际上并没有一种方法可以优雅地执行这样的操作。我建议不要使用线程取消(这可能有效,但不符合优雅的条件)。您最好的方法是使用重叠 IO。

于 2009-08-30T06:59:59.490 回答