NamedPipeClientStream 不连接

NamedPipeClientStream does not connect

在我们的主要应用程序中,我们有以下功能(在 VB.Net 中):

 Public Overrides Function GetNewResults(setToProcessed As Boolean) As List(Of ReceivedData)

    Dim client = New NamedPipeClientStream(".", "PipesOfPiece",
                                           PipeDirection.InOut, PipeOptions.None,
                                           TokenImpersonationLevel.Impersonation)
    client.Connect()
    Dim reader = New StreamReader(client)
    Dim writer = New StreamWriter(client)
    writer.AutoFlush = True

    writer.WriteLine(DbPath)

    Dim serialized = reader.ReadLine
    client.Close()

    Dim newResults = JsonConvert.DeserializeObject(Of List(Of ReceivedData))(serialized)

    Return newResults

End Function

NamedPipeServer 是用 C# 编写的,目前托管在控制台应用程序中:

 static void StartServer()
    {

        server = new NamedPipeServerStream("PipesOfPiece", direction: PipeDirection.InOut,maxNumberOfServerInstances:10);

        server.WaitForConnection();
        StreamReader reader = new StreamReader(server);
        StreamWriter writer=  new StreamWriter(server);
        writer.AutoFlush = true;

        while (true)
            {
                var dbPath = reader.ReadLine();
                if (string.IsNullOrEmpty(dbPath)) continue;
                if (!File.Exists(dbPath))
                {
                    writer.WriteLine($"{dbPath} does not exist.");
                    continue;
                }
                var communicator = new DapperBwsCommunicator(dbPath,provider: "Microsoft.Jet.OLEDB.4.0");
                var newResults = communicator.GetAllResults(setToProcessed: true);
                var serialized = JsonConvert.SerializeObject(newResults);
                writer.WriteLine(serialized);
            }
    }

GetNewResults函数每三秒调用一次。第一次调用此函数时它工作正常。但是第二次代码阻塞在 Client.Connect 上。然后服务器好像就没反应了

我哪里错了?

编辑 感谢 Fandango 的回答,我有了一个不同的实现。这似乎有效:

static void StartServer()
{

    server = new NamedPipeServerStream("PipesOfPiece", direction: PipeDirection.InOut,maxNumberOfServerInstances:10);

    server.WaitForConnection();
    StreamReader reader = new StreamReader(server);
    StreamWriter writer=  new StreamWriter(server);
    writer.AutoFlush = true;

    while (true)
        {
            var dbPath = reader.ReadLine();
            if (string.IsNullOrEmpty(dbPath)) continue;
            if (!File.Exists(dbPath))
            {
                writer.WriteLine($"{dbPath} does not exist.");
                continue;
            }
            var communicator = new DapperBwsCommunicator(dbPath,provider: "Microsoft.Jet.OLEDB.4.0");
            var newResults = communicator.GetAllResults(setToProcessed: true);
            var serialized = JsonConvert.SerializeObject(newResults);
            writer.WriteLine(serialized);
            server.Disconnnect();
            server.WaitForConnection();
        }
}

发生这种情况是因为您一直每 3 秒创建一个新的客户端连接,而在服务器端,在第一次 WaitForConnection 之后,代码卡在循环中,不再等待客户端连接。