gpt4 book ai didi

c# - NamedPipeServerStream.EndWaitForConnection() 在使用时挂起

转载 作者:可可西里 更新时间:2023-11-01 09:09:07 24 4
gpt4 key购买 nike

我是第一次尝试使用命名管道。在 MS 文档中找到 here ,它指出:

EndWaitForConnection must be called exactly once for every call to BeginWaitForConnection.

所以我想成为一名优秀的小程序员并遵循文档,但是 EndWaitForConnection() 在我使用它时会无限期地挂起。

所以我将我的代码精简到最低限度,看看我是否可以隔离问题但没有骰子。我从我编写的类(class)中提取了以下代码。我对其进行了修改,使其开始等待管道连接,然后立即尝试停止等待该管道连接:

private void WaitForConnectionCallBack(IAsyncResult result)
{

}

public void Start()
{
var tempPipe = new NamedPipeServerStream("TempPipe",
PipeDirection.In,
254,
PipeTransmissionMode.Message,
PipeOptions.Asynchronous);

IAsyncResult result = tempPipe.BeginWaitForConnection(
new AsyncCallback(WaitForConnectionCallBack), this);

tempPipe.EndWaitForConnection(result); // <----- Hangs on this line right here
}

1) 为什么它卡在 EndWaitForConnection() 上?如果我想在接收到连接之前关闭我的服务器,我该如何取消这个 BeginWaitForConnection() 回调?

2) 假设我没有遇到上述问题。如果 2 个客户端尝试快速连接到我的命名管道会怎样?

我是否为它们中的每一个都获得回调调用,或者我是否必须等待接收第一个连接通知然后快速调用 EndWaitForConnection() 然后 WaitForConnectionCallBack()再次开始监听下一个客户?

后者对我来说似乎是一种竞争条件,因为我可能没有足够快地设置连接监听器。

最佳答案

因此,适用于我的解决方案的基本框架如下:

private void WaitForConnectionCallBack(IAsyncResult result)
{
try
{
PipeServer.EndWaitForConnection(result);

/// ...
/// Some arbitrary code
/// ...
}
catch
{
// If the pipe is closed before a client ever connects,
// EndWaitForConnection() will throw an exception.

// If we are in here that is probably the case so just return.
return;
}
}

这是服务器代码。

public void Start()
{
var server= new NamedPipeServerStream("TempPipe",
PipeDirection.In,
254,
PipeTransmissionMode.Message,
PipeOptions.Asynchronous);

// If nothing ever connects, the callback will never be called.
server.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), this);

// ... arbitrary code

// EndWaitForConnection() was not the right answer here, it would just wait indefinitely
// if you called it. As Hans Passant mention, its meant to be used in the callback.
// Which it now is. Instead, we are going to close the pipe. This will trigger
// the callback to get called.

// However, the EndWaitForConnection() that will excecute in the callback will fail
// with an exception since the pipe is closed by time it gets invoked,
// thus you must capture it with a try/catch

server.Close(); // <--- effectively closes our pipe and gets our
// BeginWaitForConnection() moving, even though any future
// operations on the pipe will fail.
}

关于c# - NamedPipeServerStream.EndWaitForConnection() 在使用时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9145438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com